c# - 如何使用反射获取调用方法名称和类型?

标签 c# reflection

<分区>

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

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

C# 反射是否可行?

最佳答案

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
    }
}

关于c# - 如何使用反射获取调用方法名称和类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3095696/

上一篇:C# 清理文件名

下一篇:c# - 删除尾随零

相关文章:

c# - 过滤掉 Type.GetMethods() 返回的自动生成的方法(getter/setter/add/remove/.etc)

c# - 如何从 Unity 应用程序启动 Android Activity ?

C# - "is"运算符后的大括号的含义

C#克隆一个堆栈

c# - svcutil.exe - 错误 : Cannot import wsdl:portType

c# - 动态朗。运行时与反射

java - 如何在动态加载的 jar 中模拟方法

c# - SqlBulkCopy ColumnMapping 错误

c# - 扫描具有特定接口(interface)的 .NET 程序集的 DLL - 一些 DLL 抛出 R6034!

c# - 在结构上调用内部方法