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

时间:2016-06-02 07:45:29

标签: .net vb.net enums tostring

例如:

Enum parameter1Choices
 choice1
 choice2
End Enum

Function sampleFunction(parameter1 as parameter1Choices)
 return parameter1
End Function

所以,如果我像这样使用上述功能

sampleFunction(parameter1Choices.choice1)

我希望它会将choice1作为string

返回

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

3 个答案:

答案 0 :(得分:1)

只需使用ToString

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

答案 1 :(得分:0)

似乎答案是

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

答案 2 :(得分:0)

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

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