按变量名访问VB.Net结构元素

按变量名访问VB.Net结构元素,vb.net,reflection,structure,Vb.net,Reflection,Structure,好的,一些继承的代码:我有一个包含全部权限的结构: public structure Perms dim writeStaff as Boolean dim readStaff as Boolean dim writeSupervisor as Boolean dim readSuperVisor as Boolean ' ... and many more End Structure 我想要一个我创建的函数canDo,如下所示: public func

好的,一些继承的代码:我有一个包含全部权限的结构:

public structure Perms
    dim writeStaff as Boolean
    dim readStaff as Boolean
    dim writeSupervisor as Boolean
    dim readSuperVisor as Boolean
    ' ... and many more
End Structure
我想要一个我创建的函数canDo,如下所示:

public function canDo(p as Perms, whichOne as String) as boolean
    Dim b as System.Reflection.FieldInfo
    b = p.GetType().GetField(whichOne)
    return b
end function
我使用预填充结构和“writeSupervisor”参数调用canDo

在调试中,b显示为{Boolean writeSupervisor},但当我尝试将b返回为布尔值时,得到错误:“System.Reflection.FieldInfo”类型的值无法转换为“Boolean”

你知道我如何通过元素名和测试/比较/返回值“索引”到结构中吗

您需要调用对象的方法来获取字段值

Public Function canDo(p As Perms, whichOne As String) As Boolean
    If (Not String.IsNullOrEmpty(whichOne)) Then
        Dim info As FieldInfo = p.GetType().GetField(whichOne)
        If (Not info Is Nothing) Then
            Dim value As Object = info.GetValue(p)
            If (TypeOf value Is Boolean) Then
                Return DirectCast(value, Boolean)
            End If
        End If
    End If
    Return False
End Function

我还建议您阅读以下内容:。

很有魅力,谢谢。命名:我只是在示例中填充任何旧名称。我不得不说,虽然info.GetValue(p)将原始对象p作为参数传递,看起来非常违反直觉。太好了!我明白你的意思,但是你必须记住field info对象是通过使用对象的类型而不是对象的实例创建的。因此
p.GetType().GetField(whichOne)
GetType(Perms).GetField(whichOne)
相同。