如何检查对象是否具有与特定委托相同签名的方法
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'
}
答案 0 :(得分: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");
}
}
答案 1 :(得分: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)));