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

.net 获取我在函数中用作参数的枚举的值,.net,vb.net,enums,tostring,.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 我读过,它说我应该使用Enum.GetName,有

例如:

Enum parameter1Choices
 choice1
 choice2
End Enum

Function sampleFunction(parameter1 as parameter1Choices)
 return parameter1
End Function
如果我像这样使用上面的函数

sampleFunction(parameter1Choices.choice1)
我希望它将返回
choice1
作为
string


我读过,它说我应该使用
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
公共枚举参数选择
没有一个
第一选择
第二选择
结束枚举
导入系统
导入System.Collections.Generic
公共类选择查找
私有共享_enumLookupas Dictionary(参数选择,字符串)
共享子新()
_enumLookup=新字典(参数选择,字符串)
在[Enum].GetValues(GetType(ParameterChoice))
_enumLookup.Add(choice,choice.ToString())
下一个
端接头
公共共享函数GetChoiceValue(myChoice作为参数选项)作为字符串
GetChoiceValue=\u枚举查找(myChoice)
端函数
'防止实例化
私人分新
端接头
末级
导入系统文本
导入Microsoft.VisualStudio.TestTools.UnitTesting
公共类UnitTest1
公共子测试方法1()
Assert.AreEqual(“FirstChoice”,ChoicesLookup.GetChoiceValue(ParameterChoice.FirstChoice))
端接头
末级

是的,已经试过了。它返回0:(我将使用enum.getnames
enum.ToString()重试)
在内部调用
GetNames
方法。因此,您的自定义方法
sampleFunction
ToString
的工作完全相同。重点是什么?您好,谢谢您的回答。似乎使用
参数1.ToString
慢得多。GetName
它是基于您没有提到这是speed在你的问题中很关键。除非你调用1000次,否则它们之间的差异不太可能产生任何影响。即使这样,差异也在毫秒内。是的,我的不是速度关键。我只是想也许我可以在这里提出来。谢谢!你的答案非常简单。快速粗略的速度测试表明t ToString每次调用大约需要
0.0011ms
,而GetName每次调用大约需要
0.0006ms