首页 > 解决方案 > 给定一个将方法作为输入的方法,获取其类和方法名

问题描述

我想知道是否可以获取方法的输入函数的方法和类名。我会尝试更具体:

我有一个类Form1.cs,我在其中创建了这个方法:

public static void CalculateTime(Action<string> funcToCalc, string where)
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();

            funcToCalc(where);

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;
            // gets the textbox name
            TextBox t = Application.OpenForms["Form1"].Controls["textBox1"] as TextBox;
            // writes in the textbox of this form this string
            t.AppendText(funcToCalc.Method.Name + " executed in " + elapsedMs + "ms;\n");

        }

在这个类中,我以这种方式调用此方法:

CalculateTime( Class1.CreateStuff, textPath.Text);
CalculateTime( Class2.CreateStuff, textPath.Text);

我想做的是打印出类似的东西

"MyClass1.CreateStuff executed in 100ms"
"MyClass2.CreateStuff executed in 75ms"

等等

现在,我的方法打印出来

"CreateStuff executed in 100ms"
"CreateStuff executed in 75ms"

这不允许我识别所调用方法的类。

在这种特殊情况下,有没有办法获取类名?

请注意,如果在我的CalculateTime我打电话

System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;

我得到了字符串"Form1"

标签: c#classname

解决方案


最简单的方法是请求代表Method正在执行的方法的属性。

请注意,虽然它适用于静态和实例成员,但在匿名委托上调用时不一定有意义(当返回编译器创建的方法的无意义名称时):

using System;

public class Foo1
{
  // static
  public static void Method( string s )
  {
  } 
}
public class Foo2
{
  // instance
  public void Method( string s )
  {
  }
}

public class Program
{
  public static void  Main(string[] args)
  {
    PrintDelegateInfo( Foo1.Method );
    PrintDelegateInfo( new Foo2().Method );
    PrintDelegateInfo( (Action<string>)(s => {}) );
  }

  private static void PrintDelegateInfo(Action<string> funcToCall)
  {
    var methodInfo = funcToCall.Method;
    var name = string.Format( "{0}.{1}", methodInfo.DeclaringType.Name, methodInfo.Name );

    Console.WriteLine( "{0} called", name );
  }
}

输出:

Foo1.Method called
Foo2.Method called
Program.<Main>b__0 called

推荐阅读