2017-04-08 69 views
1

我想知道给定委托变量是否可能,以确定它是否实际指向对象方法,并且检索这个对象和方法的名字。检查委托是否是对象的方法,并检索此对象引用和方法名称

e.g:

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

回答

2

是的,它是可能的,代表包含夫妇只为性能之间。第一个是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); 
    } 
} 
+0

正是我所需要的,非常感谢你^^。 –

相关问题