获取动作/ FUNC代表的名称 [英] Get Name of Action/Func Delegate

查看:152
本文介绍了获取动作/ FUNC代表的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

和我打电话像这样

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



但是,而不是看汪汪我看到这个 < MakeDogBark> b__19。所以它看起来像它给我,使得最初的呼叫,而不是委托的名称的方法名。

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.

任何人都知道如何做到这一点?

Anyone know how to do this?

推荐答案

它给你这是委托的动作方法的名称。这恰好使用lambda表达式来实现。

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.

您已经得到了目前该又委托的调用树皮。如果你想使用树皮直接,你需要创建为树皮方法开放的委托,这可能不是非常简单。这是假设你真的想调用它。如果你不需要调用它,或者你的知道的,这将在第一个参数反正被调用,您可以使用:

You've currently got a delegate which in turn calls Bark. If you want to use Bark directly, you'll need to create an open delegate for the Bark method, 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 know that it will be called on the first argument anyway, you could use:

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

您的可能的避开这个问题通过参数表达式树,而不是代表,但如果lambda表达式只是一个方法调用反正它只会工作。

You could get 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.

这篇关于获取动作/ FUNC代表的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆