简体   繁体   中英

get the name of the method in C#

Is there any way to get the name of the method that currently we are in it?

private void myMethod()
{
    string methodName = __CurrentMethodName__;
    MessageBox(methodName);
}

Like this.ToString() that returns the class name is there any possible way to get name of the method by something like monitoring or tracing the app?

This will get you name -

string methodName = System.Reflection.MethodInfo.GetCurrentMethod().Name;

OR

string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

.NET 4.5 adds Caller Information attributes so you can use the CallerMemberNameAttribute :

using System.Runtime.CompilerServices;

void myMethod()
{
    ShowMethodName();
}

void ShowMethodName([CallerMemberName]string methodName = "")
{
    MessageBox(methodName);
}

This has the benefit of baking in the method name at compile time, rather than run time. Unfortunately there's no way to prevent someone calling ShowMethodName("Not a real Method") , but that may not be necessary.

Simply

public string MyMethod()
{
    StackTrace st = new StackTrace ();
    StackFrame sf = st.GetFrame (1);

    string methodName = sf.GetMethod().Name;
}

You can get the info about method like this

var method = MethodInfo.GetCurrentMethod();
var name = method.Name;  //get method name
var parameters = method.GetParameters();  //get method parameters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM