Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify abstract members via reflection

Tags:

c#

reflection

Given the follwing class - I would like to know which of the both members 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 there is nothing like the IsAbstract-property.
I need to select all non-abstract fields/properties/methods of a class - but there are no BindingFlags to narrow the selection, too.

like image 982
tanascius Avatar asked Jun 22 '09 06:06

tanascius


2 Answers

A property is actually some 'syntactic sugar', and is implemented by 2 methods: a getter method and a setter method.

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

PropertyInfo pi = ...

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

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

like image 187
Frederik Gheysels Avatar answered Nov 15 '22 06:11

Frederik Gheysels


First off: fields can't be abstract, since all there is to them is the field itself.

Next we note that properties are (in a loose sense!) actually get_/set_ methods under the hood.

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

Finally we remember/know/find out that a PropertyInfo has GetGetMethod() and GetSetMethod() methods that return MethodInfos, and we're done, except for filling in the messy details about inheritance and so forth.

like image 1
AakashM Avatar answered Nov 15 '22 06:11

AakashM