如何通过它的字符串名称引用枚举?

时间:2012-11-23 04:42:40

标签: vb.net types enums

我想通过其根的字符串名称来引用枚举。请注意,我想参考枚举,而不是枚举成员。

stackoverflow上有很多帖子描述了如何通过名称引用枚举成员(例如 How to retrieve an Enum member given its name),但我没有找到任何关于如何通过它的根名称来引用枚举。

进一步澄清;

Enum MyEnumA : Quiet : Noisy : End enum
Enum MyEnumB : Big : Small : Gigantic : End enum

Sub Foo(strAction as string)
    ' Depending on value of strAction, i want to create a list of either MyEnumA or MyEnumB members
    ' I know i can't do the following, it's just to make clear the direction i'm wanting to go -
    Dim lstMembers As New List(Of CType(strAction,[Enum]))   
    '....
end function

按照下面的好建议,我试过了这个;

Dim enumType As Type = System.Type.GetType("ExcelInterface.clsBTAnalyseRslts+" & "strAction")
Dim lstFldIndx As New List(Of enumtype)   'Fails to compile this line as doesn't recognize enumtype as defined

谢谢!

3 个答案:

答案 0 :(得分:1)

给它一个去,它会创建一个数组,以便您稍后可以将其更改为List(Of x ...):

Sub Foo(ByVal strAction As String)

    Dim exAssembly = Reflection.Assembly.GetExecutingAssembly

    Dim enumType = exAssembly.GetTypes.First(Function(f) f.Name = strAction)

    Dim myEnum = [Enum].GetValues(enumType)

End Sub

我发现了一篇有趣的帖子here给了我一些方向。

用法:

Foo("MyEnumA")

我会让你做一些错误处理和检查:D

答案 1 :(得分:1)

这是一个代码块,它将枚举转换为字符串,然后根据字符串获取类型。它将向您展示如何获取类型以及如何格式化字符串。其余的应该是非常直接的。

Dim obj As MyEnumA
Dim t As Type = obj.GetType()
Dim s As String = t.FullName
Dim t2 As Type = System.Type.GetType(s)

然后执行此操作以获取值:

Dim Members() As String
Members = System.Enum.GetNames(t2)

变量s看起来像这个“namespace.class + MyEnumA”,所以你需要做的就是以编程方式创建这个字符串并将其发送给一个函数。

答案 2 :(得分:0)

Ric的答案对我来说并不合适,因为我的Enum与我的代码位于同一个位置,所以这就是我最终如何管理它(我使用VB,但我会添加C#作为参考):

VB

Dim EnumName As String = "MyEnum"
Dim MyAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetAssembly(GetType(My.Assembly.Location))
Dim MyEnum As System.Type = MyAssembly.GetType("My.Assembly.Location+ClassName+" & EnumName)
Dim EnumNames As String() = MyEnum.GetEnumNames()
For intVal As Integer = 0 To EnumNames.Length - 1
    ' EnumNames(intVal) = Name of Enum Value
    ' intVal = Enum Value
Next

C#

string EnumName = "MyEnum";
System.Reflection.Assembly MyAssembly = System.Reflection.Assembly.GetAssembly(typeof(My.Assembly.Location));
System.Type MyEnum = MyAssembly.GetType("My.Assembly.Location+ClassName+" + EnumName);
string[] EnumNames = MyEnum.GetEnumNames();
for (int intVal = 0; intVal <= EnumNames.Length - 1; intVal++) {
    // EnumNames(intVal) = Name of Enum Value
    // intVal = Enum Value
}

希望它可以节省一些宝贵的时间:)。