如何使用reflection获取调用方法名称和types?

可能重复:
我怎样才能find调用当前方法的方法?

我想写一个方法获取调用方法的名称,以及包含调用方法的类的名称。

用C#reflection可能吗?

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(); } } 

名称将是“呼叫”,types将是“呼叫者”

更新两年后,因为我仍然对此感到高兴

在.Net 4.5中,现在有一个更简单的方法来做到这一点。 您可以利用CallerMemberNameAttribute

与前面的例子一起:

 public class SomeClass { public void SomeMethod([CallerMemberName]string memberName = "") { Console.WriteLine(memberName); //output will be name of calling method } } 

你可以通过使用StackTrace来使用它,然后你可以从中获得reflectiontypes。

 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); 

这实际上是可以使用当前堆栈跟踪数据和reflection的组合来完成的。

 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的方法

是的,在普林西比这是可能的,但它不是免费的。

你需要创build一个StackTrace ,然后你可以看看堆栈的StackFrame 。

从技术上讲,你可以使用StackTrace,但是这很慢,不会给你很多时间的答案。 这是因为在发布版本中可能发生优化,将删除某些方法调用。 因此,你不能确定栈跟踪是否“正确”。

真的,在C#中没有任何傻瓜或快速的方法。 你真的应该问自己,为什么你需要这个,以及如何构build你的应用程序,所以你可以做你想要的而不知道是哪个方法。