就像标题说的:反射能给你当前正在执行的方法的名字吗?
我倾向于认为不是,因为海森堡的问题。如何调用一个方法,在不改变当前方法的情况下告诉您当前方法?但我希望有人能证明我错了。
更新:
第2部分:这也可以用于在代码中查找属性吗? 第三部分:演出是什么样的?
最终结果 我学习了MethodBase.GetCurrentMethod()。我还了解到,我不仅可以创建堆栈跟踪,还可以只创建我需要的确切帧。
要在属性中使用它,只需使用. substring(4)来删除'set_'或'get_'。
就像标题说的:反射能给你当前正在执行的方法的名字吗?
我倾向于认为不是,因为海森堡的问题。如何调用一个方法,在不改变当前方法的情况下告诉您当前方法?但我希望有人能证明我错了。
更新:
第2部分:这也可以用于在代码中查找属性吗? 第三部分:演出是什么样的?
最终结果 我学习了MethodBase.GetCurrentMethod()。我还了解到,我不仅可以创建堆栈跟踪,还可以只创建我需要的确切帧。
要在属性中使用它,只需使用. substring(4)来删除'set_'或'get_'。
当前回答
Lex提供的片段有点长,所以我指出了重要的部分,因为没有其他人使用完全相同的技术:
string MethodName = new StackFrame(0).GetMethod().Name;
这将向MethodBase.GetCurrentMethod()返回相同的结果。命名技巧,但它仍然值得指出,因为我可以在它自己的方法中实现一次,使用前一个方法的索引1,并从许多不同的属性调用它。此外,它只返回一帧而不是整个堆栈跟踪:
private string GetPropertyName()
{ //.SubString(4) strips the property prefix (get|set) from the name
return new StackFrame(1).GetMethod().Name.Substring(4);
}
这也是一行代码;)
其他回答
new StackTrace().ToString().Split("\r\n",StringSplitOptions.RemoveEmptyEntries)[0].Replace("at ","").Trim()
简单的处理方法是:
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
如果系统。反射包含在using块中:
MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name;
编辑:MethodBase可能是一种更好的方法,只获取你所在的方法(而不是整个调用堆栈)。然而,我仍然担心内联。
你可以在方法中使用StackTrace:
StackTrace st = new StackTrace(true);
看看这些画框:
// The first frame will be the method you want (However, see caution below)
st.GetFrames();
但是,请注意,如果方法是内联的,则您将不在您认为的方法中。你可以使用一个属性来防止内联:
[MethodImpl(MethodImplOptions.NoInlining)]
将此方法添加到某个地方,并不带参数地调用它!
public static string GetCurrentMethodName([System.Runtime.CompilerServices.CallerMemberName] string name = "")
{
return 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