2015-04-02 159 views
2

好吧,某些遺傳代碼:我有權限的整個負載的結構:訪問VB.Net結構元素

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 

我打電話CANDO與預填充結構和「writeSupervisor」參數

在調試,b顯示爲{布爾writeSupervisor},但是當我試圖返回b爲布爾,我得到錯誤:值典型值e'System.Reflection.FieldInfo'不能轉換爲'布爾'。

任何想法如何可以通過元素名稱和測試/比較/返回值「索引」到結構?

回答

3

您需要調用FieldInfo對象的GetValue方法來獲取字段值。

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

+0

工作了一個魅力,謝謝。命名:我只是在示例中填入任何舊名稱。我不得不說,雖然info.GetValue(p),傳遞原始對象p作爲參數,似乎非常直觀。 – 2015-04-02 11:04:10

+0

太棒了!我明白你的意思,但你必須記住,字段信息對象是通過使用對象評估者的類型而不是對象的實例來創建的。所以'p.GetType()。GetField(whichOne)'和'GetType(Perms).GetField(whichOne)'是一樣的。 – 2015-04-02 11:15:11