将方法的名称作为参数传递

gor*_*kem 8 c# methods parameter-passing

private void Method1()
{
    //Do something
    Log("Something","Method1");
}

private void Method2()
{
    //Do something
    Log("Something","Method2");
}

private void Log(string message, string method)
{
    //Write to a log file
    Trace.TraceInformation(message + "happened at " + method);
}
Run Code Online (Sandbox Code Playgroud)

我有几个方法,如上面的Method1和Method2,我想有一些方法将方法的名称作为参数传递,而无需手动编辑代码.

那可能吗?

Jon*_*eet 17

从C#5开始,使用调用者信息属性非常简单:

private void Method1()
{
    //Do something
    Log("Something");
}

private void Method2()
{
    //Do something
    Log("Something");
}

private void Log(string message, [CallerMemberName] string method = null)
{
    //Write to a log file
    Trace.TraceInformation(message + "happened at " + method);
}
Run Code Online (Sandbox Code Playgroud)

在使这项工作:

  • 必须使用C#5(或更高版本)编译器,否则将无法专门处理这些属性
  • 属性必须存在于目标环境中.那里的选项:
    • 在.NET 4.5中,属性只是存在
    • 对于.NET 4,您可以使用Microsoft.BclNuGet包
    • 对于早期版本的.NET,请将属性声明复制到您自己的代码中,确保使用相同的命名空间.当您稍后迁移到新版本的.NET时,您需要再次删除它.


now*_*ed. 5

Jon Skeet的优秀答案.

但是,如果您不使用.NET 4.5,可以尝试reflection.你怎么知道这一点reflection must be used only when it is absolutely necessary. Do not over-use it for the sake of using it.

回来,你可以做点什么,

 using System.Reflection; //include Reflection namespace

 Console.WriteLine(MethodBase.GetCurrentMethod().Name) //Get the method-name of the current method
Run Code Online (Sandbox Code Playgroud)

在你的情况下,它会像下面,

private void Method1()
{
    //Do something
    Log("Something", System.Reflection.MethodBase.GetCurrentMethod().Name);
}

private void Method2()
{
    //Do something
    Log("Something", System.Reflection.MethodBase.GetCurrentMethod().Name);
}

private void Log(string message, string method)
{
    //Write to a log file
    Trace.TraceInformation(message + "happened at " + method);
}
Run Code Online (Sandbox Code Playgroud)

编辑:

根据@Jon Skeet的以下评论,如果你想要.Net 4.5一些花哨而又整洁的实现,请查看Micrsoft.BclNUGET包.