的簽名我如何檢查是否一個對象具有特定的委託檢查,如果對象有方法與委託
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'
}
的簽名我如何檢查是否一個對象具有特定的委託檢查,如果對象有方法與委託
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'
}
相同簽名的方法你可以做類型具有相同的返回類型,並且參數中的類型序列相同:
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)));
// 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");
}
}
這可行。此外,是否有可能知道'gs'是否是'o'的代表? – Fabiano 2010-01-28 09:53:58
@Fabiano:是的,通過'gs.Target':'if(gs.Target == o){/ * gs代表實例中的一個方法o * /}' – 2010-01-28 09:58:46
謝謝。我剛剛發現第二個答案對我的情況就足夠了:-) – Fabiano 2010-01-28 10:07:57