【问题标题】:Check if a delegate is a method of an object, and retrieve this object reference, and method name检查委托是否是对象的方法,并检索此对象引用和方法名称
【发布时间】:2017-04-08 18:38:12
【问题描述】:
我想知道如果给定一个委托变量,这是否可能,知道它是否实际上指向一个对象方法,并检索这个对象和方法的名称。
例如:
public delegate void test();
public static test testDel = null;
public void TestMethod()
{
;
}
public void TestDelegate()
{
//here it is not a method of an object
testDel += () => { };
// here it is "TestMethod"
testDel += this.TestMethod;
// i want something like that:
SomeDelegateInfoClass[] infos = testDel.GetAssignedObjectsAndMethodNames();
}
【问题讨论】:
标签:
c#
methods
reference
delegates
【解决方案1】:
是的,这是可能的,委托包含几个属性。第一个是Target(目标对象),第二个是Method(MethodInfo 类型)。
var target = testDel.Target; // null for static methods
var methodName = testDel.Method.Name;
但请注意,在这种情况下
testDel = () => { };
这不是“不是对象的方法”是不正确的。编译器将创建新类型,您的空匿名函数将成为该类型的方法。所以
testDel = () => { };
var targetType = testDel.Target.GetType().Name; // will be something like <>c - name of compiler-generated type
var m = testDel.Method.Name; // will be something like <Main>b__2_0 - compiler generated name
另请注意,如果您添加多个委托方法,如下所示:
testDel += () => { };
testDel += this.TestMethod;
Target 和Method 将包含有关最后添加方法的信息。要获取所有这些信息,您需要使用GetInvocationList:
if (testDel != null) {
foreach (var del in testDel.GetInvocationList()) {
Console.WriteLine(del.Target);
Console.WriteLine(del.Method);
}
}