此代码将为我们提供类的所有属性:
Dim myPropertyInfo As PropertyInfo()
= myType.GetProperties((BindingFlags.Public Or BindingFlags.Instance))
或在C#中:
PropertyInfo[] myPropertyInfo
= myType.GetProperties(BindingFlags.NonPublic|BindingFlags.Instance);
但是有没有办法只获得定义为ReadOnly的属性?
或者,同样地,排除ReadOnly属性?
答案 0 :(得分: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