C# 查找调用程序方法名
我的结构如下:C# 查找调用程序方法名,c#,.net,C#,.net,我的结构如下: public class BaseClass { public string SendError(string Message){ //which method called me return Message; } } public class TypeAClass : BaseClass { public static TypeAClass Instance { get; set;} public
public class BaseClass
{
public string SendError(string Message){
//which method called me
return Message;
}
}
public class TypeAClass : BaseClass
{
public static TypeAClass Instance { get; set;}
public void TestToTest()
{
SendError("Test Message");
}
}
我可以获取在SendError方法中调用SendError()的方法名吗。例如,在这个场景中,它应该给我一个名称TestToTest()试试这个
StackTrace stackTrace = new StackTrace();
String callingMethodName = stackTrace.GetFrame(1).GetMethod().Name;
试试这个
StackTrace stackTrace = new StackTrace();
String callingMethodName = stackTrace.GetFrame(1).GetMethod().Name;
从重复问题开始:
using System.Diagnostics;
// get call stack
StackTrace stackTrace = new StackTrace();
// get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
或者更简短地说:
new StackTrace().GetFrame(1).GetMethod().Name
从重复问题开始:
using System.Diagnostics;
// get call stack
StackTrace stackTrace = new StackTrace();
// get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
或者更简短地说:
new StackTrace().GetFrame(1).GetMethod().Name
这是C#5的一个特点:
您可以将函数的参数声明为调用方信息:
public string SendError(string Message, [CallerMemberName] string callerName = "")
{
Console.WriteLine(callerName + "called me.");
}
这是C#5的一个特点:
您可以将函数的参数声明为调用方信息:
public string SendError(string Message, [CallerMemberName] string callerName = "")
{
Console.WriteLine(callerName + "called me.");
}
可能重复的请注意使用StackFrame.GetMethod的注意事项,如中所述。。。特别是内联优化。可能的重复请注意使用StackFrame.GetMethod的注意事项,如中所述。。。特别是内联优化。