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)
在使这项工作:
Microsoft.BclNuGet包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包.