2010-01-28 30 views
8

的簽名我如何檢查是否一個對象具有特定的委託檢查,如果對象有方法與委託

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' 
    } 

回答

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))); 
+0

這可行。此外,是否有可能知道'gs'是否是'o'的代表? – Fabiano 2010-01-28 09:53:58

+1

@Fabiano:是的,通過'gs.Target':'if(gs.Target == o){/ * gs代表實例中的一個方法o * /}' – 2010-01-28 09:58:46

+0

謝謝。我剛剛發現第二個答案對我的情況就足夠了:-) – Fabiano 2010-01-28 10:07:57

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"); 
    } 
} 
+0

這似乎不起作用。 Delegate.CreateDelegate可能只適用於靜態方法嗎? – Fabiano 2010-01-28 09:50:26

+1

例如,您應該使用另一個簽名的方法,將引用傳遞給一個實例:'Delegate.CreateDelegate(gs.GetType(),o,method,false);' – torvin 2012-04-11 15:23:40