When getting the list of properties (via reflection) can we exclude ReadOnly?
This code will give us all the properties of the class:
Dim myPropertyInfo As PropertyInfo() = myType.GetProperties((BindingFlags.Public Or BindingFlags.Instance))
or in C #:
PropertyInfo[] myPropertyInfo = myType.GetProperties(BindingFlags.NonPublic|BindingFlags.Instance);
But is there a way to only get properties defined as ReadOnly?
Or, equally, to exclude the ReadOnly properties?
+3
source to share
1 answer
Just filter the results for those with CanWrite
likeFalse
Dim items As PropertyInfo() = Me. _
GetType(). _
GetProperties(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public). _
Where(Function(x) Not x.CanWrite). _
ToArray() _
Please note that the above code example assumes Visual Studio 2008
or is higher and requires import System.Linq
. If you are using an older version you can do the following
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
+6
source to share