检查委托是否是对象的方法,并检索此对象引用和方法名称



我想知道给定委托变量是否可以这样做,知道它是否实际上指向对象方法,并检索该对象和方法的名称。

例如:

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();
} 

是的,这是可能的,委托包含几个属性。第一个是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;

TargetMethod将包含有关上次添加的方法的信息。要获取有关所有这些的信息,您需要使用 GetInvocationList

if (testDel != null) {
    foreach (var del in testDel.GetInvocationList()) {
       Console.WriteLine(del.Target);
       Console.WriteLine(del.Method);
    }
}

最新更新