tags:

views:

165

answers:

2

How can I check if a object has a method with the same signature of a specific delegate

    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'
    }
+2  A: 
// 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");
    }
}
Darin Dimitrov
This doesn't seem to work. Is it possible that Delegate.CreateDelegate only works for static methods?
Fabiano
+2  A: 

You can do that by locating all methods in the type having the same return type, and the same sequence of types in the parameters:

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)));
Fredrik Mörk
this works. in addition, is it possible to find out if 'gs' is a delegate to 'o'?
Fabiano
@Fabiano: yes, through `gs.Target`: `if (gs.Target == o) { /* gs represents a method in the instance o */ }`
Fredrik Mörk
Thanks. I've just found out that the second answer would be sufficient for my case :-)
Fabiano