如何使用反射获取调用方法名称和类型? [英] How do I get the calling method name and type using reflection?

查看:19
本文介绍了如何使用反射获取调用方法名称和类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何找到调用当前的方法方法?

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

I'd like to write a method which obtains the name of the calling method, and the name of the class containing the calling method.

是否可以使用 C# 反射?

Is it possible with 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;
    }
}

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

Now let's say you have another class like this:

public class Caller
{
   public void Call()
   {
      SomeClass s = new SomeClass();
      s.SomeMethod();
   }
}

name 将是呼叫";并且类型将是来电者".

name will be "Call" and type will be "Caller".

更新:两年后,因为我仍然在此获得赞成

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

In .NET 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute.

继续上一个例子:

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

这篇关于如何使用反射获取调用方法名称和类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆