在外部程序集中反映枚举值

时间:2011-01-27 17:29:38

标签: .net reflection enums

我的目标是枚举文件夹中的DLL,查找符合特定接口的类,然后查询这些类的枚举值。这个想法是我想要查询支持“结果”的可能性。

我有我的DLL排队,可以看到符合正确接口的类,这是有效的,但下一步是在类中搜索特定的枚举并获取值,我一直在使用以下代码:

Private Sub GetOutcomeEnumValues(ByVal AssemblyPath As String, ByVal ClassName As String)
        Dim ReflectedAssembly As Assembly
        Dim ReflectedClass As Type
        'Load DLL
        ReflectedAssembly = System.Reflection.Assembly.LoadFrom(AssemblyPath)
        'Load Class
        ReflectedClass = ReflectedAssembly.GetType(ClassName)
        'Load members
        Dim Members() As MemberInfo
        Members = ReflectedClass.GetMembers
        For i As Integer = 0 To Members.Count - 1
            'Check for the Outcomes enumeration
            If (Members(i).Name = "Outcomes") Then
                Dim Outcomes As System.Array
                Outcomes = Members(i).GetType.GetEnumValues
            End If
        Next
    End Sub

我遇到的问题是,我似乎无法让会员(i)给我枚举值 - 即使我知道这个会员是一个枚举。当我调用'GetEnumValues'时会抛出异常:

“提供的类型必须是枚举。参数名称:enumType”

我正在查询的课程看起来像这样

Public Class Foo
    Public Enum Outcomes
        OK
        Cancel
    End Enum
End Class

1 个答案:

答案 0 :(得分:1)

知道了,经过一些实验,我使用下面的代码效果很好:

Private Sub GetOutcomeEnumValues(ByVal AssemblyPath As String, ByVal ClassName As String)
    Dim ReflectedAssembly As Assembly
    Dim ReflectedClass As Type
    'Load DLL
    ReflectedAssembly = System.Reflection.Assembly.LoadFrom(AssemblyPath)
    'Load Class
    ReflectedClass = ReflectedAssembly.GetType(ClassName & "+ Outcomes")
    'Load members
    Dim OutcomeNames() As String = ReflectedClass.GetEnumNames

End Sub