函数获取任何方法的名称?

Joe*_*Fan 4 c#

我想有一个名为GetMethodName的函数,以便下面的代码将打印"myMethod":

int myMethod(string foo, double bar)
{
    // ...
}

Console.Out.WriteLine(GetMethodName(myMethod));
Run Code Online (Sandbox Code Playgroud)

无论myMethod的方法签名是什么,这都应该有效.这可能吗?

Jon*_*eet 11

不,这不可能.这将有可能与神秘的infoof运营商,其C#团队会喜欢,包括,但还没有得到全面-但是没有,你不得不使用方法组转换,这如果你知道具体只会工作要使用的委托类型.

你可能最接近的是使用表达式树:

public static string GetMethodName(Expression expression)
{
    // Code to take apart the expression tree and find the method invocation
}

GetMethodName(() => myMethod(0, 0));
Run Code Online (Sandbox Code Playgroud)

这实际上不需要调用 myMethod,但你需要提供伪参数 - 如果有任何out/ref参数,这可能会令人恼火.


Mat*_*ted 5

正如Eric Lippert的博客所指出的,你可以用Action和Func代表伪造它

public static MethodInfo GetInfo<T>(Action<T> action)
{
    return action.Method;
}
public static MethodInfo GetInfo<T, TResult>(Func<T, TResult> func)
{
    return func.Method;
}
public static MethodInfo GetInfo<T, U, TResult>(Func<T, U, TResult> func)
{
    return func.Method;
}   
public static int Target(int v1, int v2)
{
    return v1 ^ v2;
} 
static int Main(string[] args)
{
    var mi = GetInfo<string[], int>(Main);
    Console.WriteLine(mi.Name);

    var mi2 = GetInfo<int, int, int>(Target);
    Console.WriteLine(mi2.Name);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)