C# 获取操作/功能委托的名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1495465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:06:22  来源:igfitidea点击:

Get Name of Action/Func Delegate

c#

提问by Adam

I have a weird situation where I need to get the Name of the delegate as a string. I have a generic method that looks like this.

我有一个奇怪的情况,我需要将委托的名称作为字符串获取。我有一个看起来像这样的通用方法。

private T Get<T>(T task, Action<T> method) where T : class
{
  string methodName = method.Method.Name //Should return Bark
}

and I am calling it like this

我是这样称呼它的

private void MakeDogBark()
{
  dog = Get(dog, x=>x.Bark());
}

But instead of seeing "Bark" I see this "<MakeDogBark>b__19". So it looks like it is giving me the method name that made the initial call instead of the name of the delegate.

但我没有看到“树皮”,而是看到了这个"<MakeDogBark>b__19"。所以看起来它给了我进行初始调用的方法名称而不是委托的名称。

Anyone know how to do this?

有人知道怎么做吗?

采纳答案by Jon Skeet

It's giving you the name of the method which is the action of the delegate. That just happens to be implemented using a lambda expression.

它为您提供了作为委托操作的方法的名称。这恰好是使用 lambda 表达式实现的。

You've currently got a delegate which in turncalls Bark. If you want to use Barkdirectly, you'll need to create an open delegate for the Barkmethod, which may not be terribly straightforward. That's assuming you actually want to call it. If you don't need to call it, or you knowthat it will be called on the first argument anyway, you could use:

您目前有一个委托,该委托调用 Bark。如果要Bark直接使用,则需要为该Bark方法创建一个开放委托,这可能不是非常简单。那是假设你真的想调用它。如果您不需要调用它,或者您知道无论如何都会在第一个参数上调用它,您可以使用:

private T Get<T>(T task, Action method) where T : class
{
   string methodName = method.Method.Name //Should return Bark
}

private void MakeDogBark()
{
   dog = Get(dog, dog.Bark);
}

You couldget round this by making the parameter an expression tree instead of a delegate, but then it would only work if the lambda expression were just a method call anyway.

可以通过使参数成为表达式树而不是委托来解决这个问题,但是只有当 lambda 表达式只是一个方法调用时它才会起作用。

回答by Rohan West

You can get the name of the method call by making the parameter an expression instead of a delegate, just like Jon mentioned

您可以通过将参数设为表达式而不是委托来获取方法调用的名称,就像 Jon 提到的

private T Get<T>(T task, Expression<Action<T>> method) where T : class
{
    if (method.Body.NodeType == ExpressionType.Call)
    {
        var info = (MethodCallExpression)method.Body;
        var name = info.Method.Name; // Will return "Bark"
    }

    //.....
}