Retrieving the name of the invoked method executed in a Func

前端 未结 3 1729
时光取名叫无心
时光取名叫无心 2020-12-18 15:03

I would like to get the name of the method that is being delegated as a Func.

Func func = x => x.DoSomeMethod();
string name = Ext         


        
3条回答
  •  一个人的身影
    2020-12-18 15:28

    Check out my hack answer here:

    Why is there not a `fieldof` or `methodof` operator in C#?

    In the past I did it another way that used Func instead of Expression>, but I was much less pleased with the result. The MemberExpression used to detect the field in my fieldof method will return a PropertyInfo when a property is used.

    Edit #1: This works for a subset of the problem:

    Func func = x.DoSomething;
    string name = func.Method.Name;
    
    
    

    Edit #2: Whoever marked me down should take a second to realize what's going on here. The expression trees can be implicitly used with lambda expressions and are the fastest, most reliable way to get the specific requested information here.

    提交回复
    热议问题