c# - 给定一个将方法作为输入的方法,获取其类和方法名
问题描述
我想知道是否可以获取方法的输入函数的方法和类名。我会尝试更具体:
我有一个类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"
。
解决方案
最简单的方法是请求代表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
推荐阅读
- apache-nifi - Apache NiFi 与 Informatica
- inno-setup - 我们可以让 DwinHs Inno Setup 下载插件运行得更快吗?
- angular - 无限循环生效
- c++ - WS_EX_TOOLWINDOW 工具窗口无法按预期工作
- json - 快速搜索字典值中的值
- asynchronous - 使用异步编程将电子邮件发送到单个 smtp 服务器是否有意义?
- php - 没有数组的PHP反向生成器
- c++ - 当用户输入“m”时,为什么我的代码不能直接进入 if 正文
- python - Dask 与 MS VS2017 一起分发
- firebase - 如何检查安全规则中引用的路径?