3

我有一个委托功能

class FuncActivator {
  public delegate void DelFunc(string arg, string val);
}

我保留该函数的实例,以便稍后在程序中同时启动(也在FuncActivator

List<DelFunc> funcList = new List<DelFunc>();

public void KeepFunc(DelFunc delFunc) {
  funcList.Add(delFunc);
}

现在我想获取有关实际委托名称的信息,或者至少是哪个类在此处传递了它。例如,在不同的班级

public class FunnyClass {
  public void FunnyFunc(string arg, string val) {
    //..Do stuff
  }

  public FunnyClass () {
    FuncActivatorInstance.KeepFunc(FunnyFunc);
  }
}

我想从一个方法中FuncActivator列出我列表中所有代表的姓名或调用者(如“FunnyFunc”或至少“FunnyClass”)。那可能吗?

4

1 回答 1

5

这段代码:

public void PrintFuncs()
{
    foreach (var func in funcList)
    {
        Console.WriteLine(func.Method.Name);
        Console.WriteLine(func.Method.DeclaringType.Name);
    }
}

印刷:

FunnyFunc
FunnyClass

FunnyClass将自身添加到列表中的实例位于 at func.Target,如果您也想使用它。

Lambdas that are attached, since they are anonymous, will have an auto-generated method name. If a class was generated for it as well, it will have an auto-generated name as well. So just FYI, you won't always be able to have very readable strings from this.

于 2012-07-09T12:10:41.700 回答