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

Access VB.Net structure element by variable name

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

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},但是当我尝试将 return b 作为布尔值时,出现错误:类型 'System.Reflection.FieldInfo' 的值无法转换为 'Boolean'.

关于如何通过元素名称和测试/比较/return 值 "index" 进入结构的任何想法?

您需要调用GetValue method of the 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