How to identify abstract members through reflection

Given the follwing class - I would like to know which of these elements is abstract:

abstract class Test { public abstract bool Abstract { get; set; } public bool NonAbstract { get; set; } } var type = typeof( Test ); var abs = type.GetProperty( "Abstract" ); var nonAbs = type.GetProperty( "NonAbstract" ); // now, something like: if( abs.IsAbstract ) ... 

Unfortunately, nothing is like IsAbstract -property.
I need to select all non-abstract fields / properties / methods of the class, but there are no BindingFlags to narrow the selection.

+4
source share
2 answers

The property is actually some “syntactic sugar” and is implemented by two methods: the getter method and the setter method.

So, I think you should be able to determine if the property is abstract by checking if the getter and / or setter are abstract, for example:

 PropertyInfo pi = ... if( pi.GetSetMethod().IsAbstract ) { } 

And, AFAIK, the field cannot be abstract .;)

+12
source

First: the fields cannot be abstract, because all that is for them is the field itself.

Further, we note that properties (in the free sense!) Actually implement the get_ / set_ methods under the hood.

Next, we check that the IsAbstract property has IsAbstract , and see what MethodBase (and so MethodInfo ) does.

Finally, we remember / know / learn that PropertyInfo has the GetGetMethod() and GetSetMethod() methods that return MethodInfo s, and we are finished, except for filling the dirty details about inheritance, etc.

+1
source

Source: https://habr.com/ru/post/1286557/


All Articles