检查对象是否具有委托签名的方法

Fab*_*ano 8 c# delegates

如何检查对象是否具有与特定委托具有相同签名的方法

    public delegate T GetSomething<T>(int aParameter);
    public static void Method<T>(object o, GetSomething<T> gs)
    {
        //check if 'o' has a method with the signature of 'gs'
    }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 7

// You may want to tweak the GetMethods for private, static, etc...
foreach (var method in o.GetType().GetMethods(BindingFlags.Public))
{
    var del = Delegate.CreateDelegate(gs.GetType(), method, false);
    if (del != null)
    {
        Console.WriteLine("o has a method that matches the delegate type");
    }
}
Run Code Online (Sandbox Code Playgroud)


Fre*_*örk 5

您可以通过查找具有相同返回类型的类型中的所有方法以及参数中相同的类型序列来实现此目的:

var matchingMethods = o.GetType().GetMethods().Where(mi => 
    mi.ReturnType == gs.Method.ReturnType
    && mi.GetParameters().Select(pi => pi.ParameterType)
       .SequenceEqual(gs.Method.GetParameters().Select(pi => pi.ParameterType)));
Run Code Online (Sandbox Code Playgroud)