How to get MethodInfo method interface by implementing MethodInfo class method?

I have MethodInfoan interface method and a Typeclass that implements an interface. I want to find MethodInfoa class method that implements an interface method.

Simple method.GetBaseDefinition()does not work with interface methods. Searching by name will also not work, because if you explicitly apply the interface method, it can have any name (yes, not in C #).

So, what is the right way to accomplish this that covers all the possibilities?

+24
source share
2 answers

Ok, I found a way using GetInterfaceMap .

var map = targetType.GetInterfaceMap(interfaceMethod.DeclaringType);
var index = Array.IndexOf(map.InterfaceMethods, interfaceMethod);

if (index == -1)
{
    //this should literally be impossible
}

return map.TargetMethods[index];
+35
source

- , , , . , , GetBaseDefinition().

(MyMethod) (MyClass), , :

MethodInfo interfaceMethodInfo = typeof(IMyInterface).GetMethod("MyMethod");
MethodInfo classMethodInfo = null;
Type[] interfaces = typeof(MyClass).GetInterfaces();

foreach (Type iface in interfaces)
{
    MethodInfo[] methods = iface.GetMethods();

    foreach (MethodInfo method in methods)
    {
        if (method.Equals(interfaceMethodInfo))
        {
            classMethodInfo = method;
            break;
        }
    }
}

, MethodInfo.Equals , . , , # 'er

EDIT

. - , , , , MethodInfo : typeof(MyClass).GetInterfaces()

MethodInfo Type, - :

classMethodINfo = typeof(MyClass)
                .GetMethods()
                .Where(m => m.Name == interfaceMethodInfo.Name)
                .Where(m => m.ReturnType == interfaceMethodInfo.ReturnType)
                .Where(m => m.GetParameters().Select(p => p.ParameterType).SequenceEqual(interfaceMethodInfo.GetParameters().Select(p => p.ParameterType)))
                .FirstOrDefault();

, , . MethodInfo, ( true ), .

- , ( ). , MethodInfo .

, , MethodInfo , , MethodInfo.Invoke.

0

Source: https://habr.com/ru/post/1719378/


All Articles