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

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

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method\">How我能找到调用当前方法的方法?


我想写其获得调用方法的名称的方法,以及含有该调用方法的类的名字。

是否有可能与C#反射?


解决方案

 公共类SomeClass的
{
    公共无效的someMethod()
    {
        的StackFrame帧=新的StackFrame(1);
        VaR方法= frame.GetMethod();
        VAR类型= method.DeclaringType;
        变量名称= method.Name;
    }
}

现在让我们假设你有另一个类是这样的:

 公共类来电
{
   公共无效调用()
   {
      SomeClass的S =新SomeClass的();
      s.SomeMethod();
   }
}

名称将是呼叫,然后键入会来电

UPDATE两年后,因为我仍然在这个越来越upvotes

在.NET 4.5现在有这样做更简单的方法。您可以利用的<一个href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute%28v=vs.110%29.aspx\"><$c$c>CallerMemberNameAttribute

在previous例子状况:

 公共类SomeClass的
{
    公共无效的someMethod([CallerMemberName]字符串memberName =)
    {
        Console.WriteLine(memberName); //输出将我拨打方法的名称
    }
}

Possible Duplicate:
How can I find the method that called the current method?

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.

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 will be "Call" and type will be "Caller"

UPDATE Two years later since I'm still getting upvotes on this

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

Going with the previous example:

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

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

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