mercredi 8 mai 2019

How detect is a method in a C# class is implementing a method from an interface?

I want to be able to use reflection to tell that an implementation of the method GetName in SomClassImpl comes from the interface IHasName. As an example:

public interface IHasName
{
    string GetName();
}

public interface IOtherInterface
{
    //...elided...
}

public class MyClass : IHasName, IOtherInterface
{
    /*
     * I want to use reflection to know this 
     * implements IHasName.GetName()
     */
    public string GetName()
    {
        return "me";
    }
}

Is this possible?

When I tried typeof(MyClass).GetMethod("GetName").GetBaseDefinition().DeclaringType and typeof(MyClass).GetMethod("GetName").DeclaringType, they both return the implementing class, not the interface.





Aucun commentaire:

Enregistrer un commentaire