给定一个以方法作为输入的方法,获取其类和方法名称

时间:2019-06-25 08:47:27

标签: c# classname

我想知道是否有可能获得方法和方法输入功能的类名。我会尝试更具体:

我有一个类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"

2 个答案:

答案 0 :(得分:4)

最简单的方法是要求委托者的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

答案 1 :(得分:3)

您可以在操作本身上使用扩展方法GetMethodInfo(Delegate),以获取委托的MethodInfo。 假设您没有像Lambda函数那样传递匿名类型的委托,则可以使用此MethodInfo通过DeclaringType获取类类型,如下所示:

public static void CalculateTime(Action<string> funcToCalc, string where)
    {   
        var miAction = funcToCalc.GetMethodInfo();
        var actionContainingType = miAction.DeclaringType;
        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($"{actionContainingType.Name}.{funcToCalc.Method.Name} executed in {elapsedMs} ms;\n");

    }