简体   繁体   English

在C#中获取方法的名称

[英]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.ToString()返回类名是否有任何可能的方法来通过监视或跟踪应用程序来获取方法的名称?

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 : .NET 4.5添加了Caller Information属性,因此您可以使用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. 不幸的是,没有办法阻止有人调用ShowMethodName("Not a real Method") ,但这可能没有必要。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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