获取我在函数中用作参数的枚举值

Get the value of the enum that I used as parameter in my function

例如:

Enum parameter1Choices
 choice1
 choice2
End Enum

Function sampleFunction(parameter1 as parameter1Choices)
 return parameter1
End Function

所以如果我像这样使用上面的函数

sampleFunction(parameter1Choices.choice1)

我预计它将 return choice1string

我读过 this,它说我应该使用 Enum.GetName,有些人说 .ToString。我该如何使用它?

好像答案是

Function sampleFunction(parameter1 As parameter1Choices) As String
    Return [Enum].GetName(GetType(parameter1Choices), parameter1)
End Function

只需使用ToString:

Function sampleFunction(parameter1 As parameter1Choices) As String
    Return parameter1.ToString()
End Function

如果速度是个大问题,您可以尝试在字典中查找值

Public Enum ParameterChoice
    None
    FirstChoice
    SecondChoice
End Enum

Imports System
Imports System.Collections.Generic

Public Class ChoicesLookup
    Private Shared _enumLookup As Dictionary(Of ParameterChoice, String)
    Shared Sub New()
        _enumLookup = New Dictionary(Of ParameterChoice, String)
        For Each choice As ParameterChoice In [Enum].GetValues(GetType(ParameterChoice))
            _enumLookup.Add(choice, choice.ToString())
        Next
    End Sub

    Public Shared Function GetChoiceValue(myChoice As ParameterChoice) As String
        GetChoiceValue = _enumLookup(myChoice)
    End Function

    'prevents instantiation
     Private Sub New()
     End Sub
End Class

Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting

<TestClass()> Public Class UnitTest1

    <TestMethod()> Public Sub TestMethod1()
        Assert.AreEqual("FirstChoice", ChoicesLookup.GetChoiceValue(ParameterChoice.FirstChoice))
    End Sub
End Class