就像标题说的:反射能给你当前正在执行的方法的名字吗?
我倾向于认为不是,因为海森堡的问题。如何调用一个方法,在不改变当前方法的情况下告诉您当前方法?但我希望有人能证明我错了。
更新:
第2部分:这也可以用于在代码中查找属性吗? 第三部分:演出是什么样的?
最终结果 我学习了MethodBase.GetCurrentMethod()。我还了解到,我不仅可以创建堆栈跟踪,还可以只创建我需要的确切帧。
要在属性中使用它,只需使用. substring(4)来删除'set_'或'get_'。
就像标题说的:反射能给你当前正在执行的方法的名字吗?
我倾向于认为不是,因为海森堡的问题。如何调用一个方法,在不改变当前方法的情况下告诉您当前方法?但我希望有人能证明我错了。
更新:
第2部分:这也可以用于在代码中查找属性吗? 第三部分:演出是什么样的?
最终结果 我学习了MethodBase.GetCurrentMethod()。我还了解到,我不仅可以创建堆栈跟踪,还可以只创建我需要的确切帧。
要在属性中使用它,只需使用. substring(4)来删除'set_'或'get_'。
当前回答
为了同时处理异步和普通的旧方法调用,我这样做了。
在我的应用程序中,它只从异常处理程序调用,所以性能不是一个问题。
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetCurrentMethodName()
{
var st = new StackTrace();
var sf = st.GetFrame(1);
string name = sf.GetMethod().Name;
if (name.Equals("MoveNext"))
{
// We're inside an async method
name = sf.GetMethod().ReflectedType.Name
.Split(new char[] { '<', '>' }, StringSplitOptions.RemoveEmptyEntries)[0];
}
return name;
}
其他回答
在空控制台程序的Main方法中试试这个:
MethodBase method = MethodBase.GetCurrentMethod();
Console.WriteLine(method.Name);
控制台输出: 主要
new StackTrace().ToString().Split("\r\n",StringSplitOptions.RemoveEmptyEntries)[0].Replace("at ","").Trim()
我认为你应该能够从创建一个StackTrace。或者,正如@edg和@Lars Mæhlum提到的,MethodBase.GetCurrentMethod()
这个怎么样:
StackFrame frame = new StackFrame(1);
frame.GetMethod().Name; //Gets the current method name
MethodBase method = frame.GetMethod();
method.DeclaringType.Name //Gets the current class name
从2021年到2022年,为客户提供更具弹性的解决方案:
namespace my {
public struct notmacros
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string
whoami( [CallerMemberName] string caller_name = null)
{
if (string.IsNullOrEmpty(caller_name))
return "unknown";
if (string.IsNullOrWhiteSpace(caller_name))
return "unknown";
return caller_name;
}
}
} // my namespace
使用
using static my.notmacros
// somewhere appropriate
var my_name = whoami() ;
.NET小提琴链接的实际演示:
https://dotnetfiddle.net/moK73n
请注意编译器要求:.NET 6