从Value获取VB.net枚举描述 [英] Get VB.net Enum Description from Value
问题描述
$ p
我可以从名称中获取描述。 :
公共共享函数GetEnumDescription(ByVal EnumConstant As [Enum])As String
Dim fi As FieldInfo = EnumConstant。 GetType()GetField(EnumConstant.ToString())
Dim attr()As DescriptionAttribute = _
DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute),_
False),DescriptionAttribute )
如果attr.Length> 0然后
返回attr(0).Description
Else
返回EnumConstant.ToString()
如果
结束函数
但是我不知道如何将变量名称传递给这个函数。我尝试过这样的东西,如
GetEnumDescription([Enum] .GetName(GetType(myEnum),2)))
但我没有尝试过的是正确的。
如果你有一个枚举类型的变量,它只是简单的
GetEnumDescription(myEnum)
最小工作示例:
枚举TestEnum
<描述(Value1的描述)>
Value1
End Enum
Public Sub Main()
Dim myEnum As TestEnum = TestEnum.Value1
Console.WriteLine(GetEnumDescription(myEnum))'打印Value1的描述
Console.ReadLine()
End Sub
如果您有一个整数
变量,则需要先将其转换为您的枚举类型( CType
工作):
GetEnumDescription(DirectCast(myEnumValue,TestEnum))
工作示例:
枚举TestEnum
<描述(Value1的描述)>
Value1 = 1
End Enum
Public Sub Main()
Console.WriteLine(GetEnumDescription(DirectCast(1,TestEnum)))
控制台。 ReadLine()
End Sub
你的困惑的来源似乎是一个误会:你的方法不将枚举的名称作为参数,它需要一个枚举
作为参数。这是不同的,这也是您尝试使用 GetName
失败的原因。
How can I get Enum
description from its value?
I can get the description from the name using:
Public Shared Function GetEnumDescription(ByVal EnumConstant As [Enum]) As String
Dim fi As FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())
Dim attr() As DescriptionAttribute = _
DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute), _
False), DescriptionAttribute())
If attr.Length > 0 Then
Return attr(0).Description
Else
Return EnumConstant.ToString()
End If
End Function
But I cant figure out how to pass a variable name to this function. I've tried things like
GetEnumDescription([Enum].GetName(GetType(myEnum), 2)))
but nothing I've tried is correct.
If you have a variable of your enum type, it's simply
GetEnumDescription(myEnum)
Minimal working example:
Enum TestEnum
<Description("Description of Value1")>
Value1
End Enum
Public Sub Main()
Dim myEnum As TestEnum = TestEnum.Value1
Console.WriteLine(GetEnumDescription(myEnum)) ' prints "Description of Value1"
Console.ReadLine()
End Sub
If you have an Integer
variable, you need to cast it to your enum type first (CType
works as well):
GetEnumDescription(DirectCast(myEnumValue, TestEnum))
Working example:
Enum TestEnum
<Description("Description of Value1")>
Value1 = 1
End Enum
Public Sub Main()
Console.WriteLine(GetEnumDescription(DirectCast(1, TestEnum)))
Console.ReadLine()
End Sub
The source for your confusion seems to be a misunderstanding: Your method does not take the "name" of an enum as a parameter, it takes an Enum
as a parameter. That's something different, and it's also the reason why your attempts to use GetName
failed.
这篇关于从Value获取VB.net枚举描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!