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();
}
}
name将会是"Call",type将会是"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
}
}
[CallerMemberName]
方案时,编译器会全权处理整个过程,因此在运行时不需要实际反射,这有助于提高性能。 - Grochni[CallerTypeName]
可以获取调用方法的声明类型... - cube45StackTrace
,然后从中获取反射类型。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);
其实可以通过当前的堆栈跟踪数据和反射来完成这项操作。
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
方法的方法名称。