问题描述
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);
}
我有几种方法,例如上面的Method1和Method2,我想以某种方式将方法的名称作为参数传递,而无需手动编辑代码.
I have several methods like Method1 and Method2 above, and i would like some way pass the method's name as a parameter, without manually editing the code.
有可能吗?
推荐答案
乔恩·斯凯特(Jon Skeet)的出色回答.
Excellent answer from 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
.
However, if you don't use .NET 4.5
, you can try reflection
. How ever you should know that reflection must be used only when it is absolutely necessary. Do not over-use it for the sake of using it
.
回来,您可以做类似的事情,
Coming back,You could do something like,
using System.Reflection; //include Reflection namespace
Console.WriteLine(MethodBase.GetCurrentMethod().Name) //Get the method-name of the current method
在您的情况下,如下所示,
In your case, it would be like below,
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);
}
根据@Jon Skeet的以下评论,如果您想要.Net 4.5
那种精美而整洁的实现,请查看Micrsoft.Bcl
NUGET软件包.
As per the below comments from @Jon Skeet's, if you want .Net 4.5
kind of fancy and neat implementation, check out the Micrsoft.Bcl
NUGET Package.
这篇关于传递方法名称作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!