2016-12-19 117 views
0

有沒有辦法通過propertyinfo對象獲取對象屬性的值?使用propertyinfo對象獲取屬性值

psudo代碼:

propertyinfoObject = Text 
myobject.toCommand(propertyinfoObject) 

上面的psudo代碼應該做的一樣

myobject.Text 

我的目標是創建一個simpel屬性形成將任何物體上工作(後來,我將使用關鍵字來篩選出我希望使用的選項)。

我真正的代碼

Public Class PropertiesForm 
Dim propertyInfoVar() As PropertyInfo 
Dim Properties As New Form2 
Dim listItem As New ListViewItem 
Dim stringarray() As String 
Public Sub New(ByRef sender As Object) 



    propertyInfoVar = sender.GetType().GetProperties() 
    For Each p In propertyInfoVar 
     stringarray = {p.Name.ToString, #INSERT VALUE SOMEHOW HERE#} 

     listItem = New ListViewItem(stringarray) 
     Properties.ListView1.Items.Add(listItem) 
    Next 
    Properties.Visible = True 
End Sub 

編輯 只要使用PropertyGrid的如下建議!

+1

不是沒有,但PropertyGrid已經沒有這麼做了嗎? – Plutonix

+0

:)你是那麼正確!我不知道它存在。 .net框架非常龐大,當你是新的時候,很容易錯過關鍵的東西:)。也許我應該從頭到尾閱讀我的VB書,而不僅僅是跳到它! – implor

+0

如果答案解決了您的問題,請單擊旁邊的複選標記,以便將其從UnAnswered列表中移除。接受答案和(稍後)提出問題或答案,你會發現有用的幫助他人找到好的答案。 [Tour]非常短,解釋了SO的工作原理。 – Plutonix

回答

0

標準PropertyGrid已經爲你做了所有的事情。過濾屬性不是那麼明顯,這裏是如何:

該控件包括BrowsableAttributes屬性,它允許您指定只應顯示具有指定屬性值的屬性。您可以使用現有屬性或自定義屬性。這是專門用於標記可見道具:

<AttributeUsage(AttributeTargets.Property)> 
Public Class PropertyGridBrowsableAttribute 
    Inherits Attribute 

    Public Property Browsable As Boolean 

    Public Sub New(b As Boolean) 
     Browsable = b 
    End Sub 
End Class 

將它應用到一個Employee類隱藏工資率或其他任何東西:

Public Class Employee 
    <PropertyGridBrowsable(True)> 
    Public Property FirstName As String 
    ... 
    <PropertyGridBrowsable(False)> 
    Public Property PayRate As Decimal 
    <PropertyGridBrowsable(False)> 
    Public Property NationalInsuranceNumber As String 

測試代碼:

Dim emp As New Employee With {.Dept = EmpDept.Manager, 
            .FirstName = "Ziggy", 
            .PayRate = 568.98D, 
            ... 
            .NationalInsuranceNumber = "1234567" 
            } 

propGrid.BrowsableAttributes = New AttributeCollection(New PropertyGridBrowsableAttribute(True)) 

propGrid.SelectedObject = emp 

enter image description here

BrowsableAttributes是一個集合,所以你可以添加幾個。