[英]c# Get Calling Method Without Stack Trace
我注意到.NET 4.5有一个名为[CallerMemberNameAttribute]的新属性,当附加到方法的参数时,它将提供调用该方法的方法的字符串名称(如果这有意义)。
然而,不幸的是(因为我想用XNA制作东西)我只针对.NET 4.0。
我希望能够做到这样的事情:
void MethodA() {
MethodB();
}
void MethodB() {
string callingMethodName = (...?);
Console.WriteLine(callingMethodName);
}
我的输出是MethodA 。
我知道我可以通过堆栈跟踪来做到这一点,但那是a)不可靠和b)Sloooow ...所以我想知道是否还有其他方法可以收集这些信息,但这可能是......
我希望任何人都可以在这个问题上有任何想法或知识。 提前致谢 :)
如果使用Visual Studio 2012进行编译,则可以编写自己的CallerMemberNameAttribute
并使用与.NET 4.5相同的方法,即使您仍然使用.NET 4.0或3.5。 编译器仍将在编译时执行替换,甚至针对较旧的框架版本。
只需将以下内容添加到项目中即可:
namespace System.Runtime.CompilerServices
{
public sealed class CallerMemberNameAttribute : Attribute { }
}
您可以将调用者名称作为参数提供给被调用方法。 不是你要求的,但它无需访问堆栈框架即可运行:
[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
标记您的调用方法,以避免方法内联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.