Reputation: 20697
We are giving some repetitive jobs to a consultant company, we just have a few constraints that could not be checked by compilation, like a requirement to override a specific property in all class implementing a specific interface.
The property of the interface, which should be overrided in all classes has the following signature:
dynamic Definition{get;}
I found this stackoverflow question: How to find out if property is inherited from a base class or declared in derived?
Which is closed to my case, but in my case, the property is defined is inherited class and overrided in this one:
public class ClassA:IMyInterface
{
public virtual dynamic Definition{get{ /*return SomethingSpecificToClassA;*/}}
}
public class ClassB:ClassA
{
public override dynamic Definition{get{ /*return SomethingSpecificToClassB;*/}}
}
//The end goal is to know if ClassB has correctly overriden the property
bool overriden = typeof(ClassB)GetProperties(...).Any(p=>p.Name=="Definition");
Upvotes: 1
Views: 104
Reputation: 111810
This is the solution: you ask ClassB
its interface map, you look for the method you want in the interface map and then you look where the implementation method (classMethod
) is declared.
var interfaceMethod = typeof(I).GetProperty("Definition").GetGetMethod();
var map = typeof(ClassB).GetInterfaceMap(typeof(I));
var ix = Array.IndexOf(map.InterfaceMethods, interfaceMethod);
var classMethod = map.TargetMethods[ix];
bool isDeclaredInClass = classMethod.DeclaringType == typeof(ClassB);
Upvotes: 1
Reputation: 16878
You can find for property declared only in your type of interests:
var prop = typeof (ClassB).GetProperty("Definition", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
Then you can then check if its getter is virtual:
prop.GetMethod.IsVirtual
which will be false
if Definition
hides (or uses new
) in ClassB
Upvotes: 0