mercredi 11 mai 2016

Determine method that implements/overrides interface using reflection in .NET

How can I use reflection to determine what method will be called given a Type that implements (or inherits an implementation of) an interface and a MethodInfo of the method from that interface?

Consider the following classes:

using System;

public class A : IDisposable {
    public virtual void Dispose() { Console.WriteLine("A.Dispose"); }
}

public class B : A {
    public new virtual void Dispose() { Console.WriteLine("B.Dispose"); }
}

public class C : A, IDisposable {
    public new virtual void Dispose() { Console.WriteLine("C.Dispose"); }
}

public class D : A, IDisposable {
    void IDisposable.Dispose() { Console.WriteLine("D.IDisposable.Dispose"); }
}

public class Program
{
    public static void Main()
    {
        ((IDisposable)new A()).Dispose(); // A.Dispose
        ((IDisposable)new B()).Dispose(); // A.Dispose
        ((IDisposable)new C()).Dispose(); // C.Dispose
        ((IDisposable)new D()).Dispose(); // D.IDisposable.Dispose
    }
}

I suppose I could do a brute-force search for the most derived method

  • with the same signature
  • and with either the name or qualified name of the interface method
  • and ignore newslot methods in classes that inherit (rather than implement) the interface
  • and ignore any overrides of ignored methods
  • and ...

It gets to be a complex list of corner cases which will be hard to get right, not to mention that it would miss overrides with unrelated names which can be created using TypeBuilder.DefineMethodOverride.

Is there a better way to do this?





Aucun commentaire:

Enregistrer un commentaire