这段代码将为我们提供类的所有属性:
Dim myPropertyInfo As PropertyInfo()
= myType.GetProperties((BindingFlags.Public Or BindingFlags.Instance))
Run Code Online (Sandbox Code Playgroud)
或者在C#中:
PropertyInfo[] myPropertyInfo
= myType.GetProperties(BindingFlags.NonPublic|BindingFlags.Instance);
Run Code Online (Sandbox Code Playgroud)
但有没有办法获得定义为ReadOnly的属性?
或者,同样地,排除ReadOnly属性?
只需将结果过滤到那些具有CanWriteas 的结果False
Dim items As PropertyInfo() = Me. _
GetType(). _
GetProperties(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public). _
Where(Function(x) Not x.CanWrite). _
ToArray() _
Run Code Online (Sandbox Code Playgroud)
请注意,上面的代码示例是假设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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
508 次 |
| 最近记录: |