Get Name of Action/Func Delegate

前端 未结 2 1625
说谎
说谎 2020-12-24 01:20

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 tas         


        
相关标签:
2条回答
  • 2020-12-24 01:24

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

    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"
        }
    
        //.....
    }
    
    0 讨论(0)
  • 2020-12-24 01:44

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

    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.

    0 讨论(0)
提交回复
热议问题