I have a derived class with a method that overrides开发者_如何转开发 the base class's method, (like this) but module.ResolveMethod(token, typeArguments, methodArguments)
gives me a MethodBase with a declaringType of the base type, not the derived type like it should be.
Is this a bug in module.ResolveMethod
?
The code is fairly complex to post, but I am using Jb Evain's MethodBaseRocks
No, you are using reflection/IL inspection. This is static code analysis. You are not doing anything on a specific runtime instance of a type.
Polymorphism is 'evaluated' at runtime: the runtime decides (based on the actual type of the object) which version of the virtual method to call (base or derived).
Your code seems to look a method up on a specific type, which will by definition return the method from that type, because you are inspecting the metadata as it is (the base declares the base method, the derived declares the derived method, nothing fancy; it's just the facts).
I think (IIRC) Mono.Cecil (from JbEvain) exposes an Overloads collection on the MethodDefinition. I suppose you may have to call MethodReference.Resolve() in order to get the MethodDefinition.
more background if desired:
There is no safe reflection way to invoke a virtual method according to runtime rules that apply when doing a callvirt
in CIL. I.e. even if you do:
class BaseClass
{ public virtual void SomeMethod() {} }
class Derived :BaseClass {}
class MainClass
{
public static void Main (string[] args)
{
Expression<Action<Derived>> expr = (instance) => instance.SomeMethod();
var method = (expr.Body as MethodCallExpression).Method;
Console.WriteLine(method.DeclaringType);
}
}
it will print NamespaceName.BaseClass
because it is the class that declares the virtual.
精彩评论