可能重复:
How can I find the method that called the current method?
我想写一个方法,它获取调用方法的名称,以及包含调用方法的类的名称。
是否可以使用C#反射?
发布于 2010-06-23 01:57:12
public class SomeClass
{
public void SomeMethod()
{
StackFrame frame = new StackFrame(1);
var method = frame.GetMethod();
var type = method.DeclaringType;
var name = method.Name;
}
}
现在假设你有另一个这样的类:
public class Caller
{
public void Call()
{
SomeClass s = new SomeClass();
s.SomeMethod();
}
}
名称为"Call“,类型为"Caller”。
更新:两年后,我仍然在这个上获得好评
在.NET 4.5中,现在有一种更简单的方法来实现这一点。您可以利用CallerMemberNameAttribute
。
使用前面的示例:
public class SomeClass
{
public void SomeMethod([CallerMemberName]string memberName = "")
{
Console.WriteLine(memberName); // Output will be the name of the calling method
}
}
发布于 2010-06-23 01:56:45
你可以通过使用StackTrace
来使用它,然后你就可以从中获得反射类型。
StackTrace stackTrace = new StackTrace(); // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
StackFrame callingFrame = stackFrames[1];
MethodInfo method = callingFrame.GetMethod();
Console.Write(method.Name);
Console.Write(method.DeclaringType.Name);
发布于 2010-06-23 01:59:05
这实际上是可以使用当前堆栈跟踪数据和反射的组合来完成的事情。
public void MyMethod()
{
StackTrace stackTrace = new System.Diagnostics.StackTrace();
StackFrame frame = stackTrace.GetFrames()[1];
MethodInfo method = frame.GetMethod();
string methodName = method.Name;
Type methodsClass = method.DeclaringType;
}
StackFrame
数组上的1
索引将为您提供名为MyMethod
的方法
https://stackoverflow.com/questions/3095696
复制相似问题