Passing a method's name as a parameter

落爺英雄遲暮 提交于 2019-12-10 03:05:43

问题


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);
}

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.

Is that possible?


回答1:


Excellent answer from Jon Skeet.

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);
}

EDIT:

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.




回答2:


As of C# 5, this is really easy using caller info attributes:

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);
}

In terms of getting this working:

  • You must be using the C# 5 (or later) compiler, otherwise it won't know to handle the attributes specially
  • The attributes have to exist in your target environment. Options there:
    • In .NET 4.5 the attributes are simply present
    • For .NET 4 you can use the Microsoft.Bcl NuGet package
    • For earlier versions of .NET, copy the attribute declaration into your own code, making sure you use the same namespace. When you later move to a new version of .NET, you'll need to remove it again.



回答3:


Aspect Oriented Programming (AOP) usually allows to achieve such tasks. You can have a look at the free version of PostSharp, especially the Logging aspect is helpful in your case.

Your code then looks like this:

[LogAspect("Something")]
void Method1(string name)
{

}

You can use PostSharp down to .NET framework 2.0.



来源:https://stackoverflow.com/questions/21230580/passing-a-methods-name-as-a-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!