38

I am trying to find ways to log method name in an efficient manner w.r.t. speed and maintainability. I guess, In .NET 4.5 Caller Information attributes are exposed just for this purpose except the speed part. I feel these are just syntactic sugars from using System.Reflection.MethodBase.GetCurrentMethod() or stackTrace.GetFrame(1).GetMethod().Name (Got from here). (or) Are these methods give performance benefits too?

In C#, Is there a way to get method name at compile time (as like in C++)?

4

1 回答 1

87

调用者信息属性使 C# 编译器在调用点提供调用者的名称。这发生在编译时,不涉及反射。

public void DoProcessing()
{
    LogCall();
}

public void LogCall([CallerMemberName] string memberName = "")
{
     Console.WriteLine(memberName + " was called.");
}

将编译为:

public void DoProcessing()
{
    LogCall("DoProcessing");
}

public void LogCall(string memberName)
{
     Console.WriteLine(memberName + " was called.");
}
于 2013-04-19T09:28:11.913 回答