2012-03-23 71 views
3

此代碼將讓我們一類的所有屬性:獲取屬性列表(通過反射)時,我們是否可以排除ReadOnly?

Dim myPropertyInfo As PropertyInfo() 
    = myType.GetProperties((BindingFlags.Public Or BindingFlags.Instance)) 

或C#:

PropertyInfo[] myPropertyInfo 
    = myType.GetProperties(BindingFlags.NonPublic|BindingFlags.Instance); 

但是,有沒有辦法讓剛剛定義爲只讀屬性?

或者,同樣,排除ReadOnly屬性?

回答

6

只要篩選結果到那些具有CanWrite作爲False

Dim items As PropertyInfo() = Me. _ 
    GetType(). _ 
    GetProperties(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public). _ 
    Where(Function(x) Not x.CanWrite). _ 
    ToArray() _ 

注意上面的代碼示例是假設Visual Studio 2008或更高,並且需要的System.Linq導入。如果您使用的是舊版本,您可以執行以下操作:

Dim props As PropertyInfo() = Me.GetType().GetProperties(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public) 
Dim readOnlyProps As New List(Of PropertyInfo) 
For Each cur in props 
    If Not cur.CanWrite Then 
    readOnlyProps.Add(cur) 
    End If 
Next 
+0

謝謝Jared, – hawbsl 2012-03-23 16:10:00

相關問題