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

时间:2015-04-02 09:01:51

标签: 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 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

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

我是如何通过元素名称和测试/比较/返回值“索引”到结构中的?

1 个答案:

答案 0 :(得分:4)

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

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

我还建议你阅读:Visual Basic Naming Conventions