C # Get call method without stack trace

I noticed that .NET 4.5 has a new attribute [CallerMemberNameAttribute] , which when attached to a method parameter will provide the string name of the method that called this method (if that makes sense).

However, unfortunately (because I want to do something with XNA), I am only targeting .NET 4.0.

I want to be able to do something like:

void MethodA() {
   MethodB();
}

void MethodB() {
   string callingMethodName = (...?);
   Console.WriteLine(callingMethodName);
}

Where my conclusion will be MethodA.

I know that I can do this with a stack trace, but that a) is unreliable and b) Sloooow ... So I wonder if there is any other way to get this information, however it could be ...

I was hoping for any ideas or knowledge that any person might have on this issue. Thanks in advance:)

+5
2

Visual Studio 2012 , CallerMemberNameAttribute , .NET 4.5, .NET 4.0 3.5. , .

:

namespace System.Runtime.CompilerServices
{
    public sealed class CallerMemberNameAttribute : Attribute { }
}
+13

. , , :

[MethodImpl(MethodImplOptions.NoInlining)]
void MethodA() 
{
    string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
    MethodB(methodName);
}

void MethodB(string callingMethodName) 
{
    Console.WriteLine(callingMethodName);
}

MethodBase.GetCurrentMethod(), , - , - .

MethodImplOptions.NoInlining, inline-.

0

All Articles