![](/img/trans.png)
[英]In C#, how can I get the name of the calling project from within a referenced project?
[英]How can I get the name of the calling function in C#?
我需要获取C#中调用函数的名称。 我读到有关stackframe方法的信息,但是到处都说它不可靠并且会影响性能。
但我需要将其用于生产。 我正在编写一个自定义跟踪程序,它将记录从中调用跟踪的方法的名称。
有人可以提供一种有效的方法来获取调用函数名称的方法吗? 我正在使用Visual Studio 2010。
升级到c#5并使用CallerMemberName
public void Method([CallerMemberName] string caller="")
{
}
编辑
C#5的其他优点
public void Method([CallerMemberName] string name="",
[CallerLineNumber] int line=-1,
[CallerFilePath] string path="")
{
}
您可以通过简单地声明LB(在.NET 3.5或更高版本中)使用LB答案中提到的C#4.5属性(您需要使用vs2012或更高版本进行编译,否则不会出现任何错误,但参数值将保持为null! ):
namespace System.Runtime.CompilerServices
{
[AttributeUsageAttribute(AttributeTargets.Parameter, Inherited = false)]
public sealed class CallerMemberNameAttribute : Attribute
{
}
[AttributeUsageAttribute(AttributeTargets.Parameter, Inherited = false)]
public sealed class CallerFilePathAttribute : Attribute
{
}
[AttributeUsageAttribute(AttributeTargets.Parameter, Inherited = false)]
public sealed class CallerLineNumberAttribute : Attribute
{
}
}
您可以执行以下操作:
var stackTrace = new StackTrace();
var name = stackTrace.GetFrame(1).GetMethod().Name;
它可以与任何版本的框架/语言一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.