首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用反射获取调用方法的名称和类型?

如何使用反射获取调用方法的名称和类型?
EN

Stack Overflow用户
提问于 2010-06-23 01:51:07
回答 5查看 124.2K关注 0票数 168

可能重复:

How can I find the method that called the current method?

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

是否可以使用C#反射?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-06-23 01:57:12

代码语言:javascript
复制
public class SomeClass
{
    public void SomeMethod()
    {
        StackFrame frame = new StackFrame(1);
        var method = frame.GetMethod();
        var type = method.DeclaringType;
        var name = method.Name;
    }
}

现在假设你有另一个这样的类:

代码语言:javascript
复制
public class Caller
{
   public void Call()
   {
      SomeClass s = new SomeClass();
      s.SomeMethod();
   }
}

名称为"Call“,类型为"Caller”。

更新:两年后,我仍然在这个上获得好评

在.NET 4.5中,现在有一种更简单的方法来实现这一点。您可以利用CallerMemberNameAttribute

使用前面的示例:

代码语言:javascript
复制
public class SomeClass
{
    public void SomeMethod([CallerMemberName]string memberName = "")
    {
        Console.WriteLine(memberName); // Output will be the name of the calling method
    }
}
票数 435
EN

Stack Overflow用户

发布于 2010-06-23 01:56:45

你可以通过使用StackTrace来使用它,然后你就可以从中获得反射类型。

代码语言:javascript
复制
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);
票数 21
EN

Stack Overflow用户

发布于 2010-06-23 01:59:05

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

代码语言:javascript
复制
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的方法

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3095696

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档