在C#中动态获取方法名称最简单、最便宜的方法是什么
本文关键字:方法 最简单 最便宜 是什么 动态 获取 | 更新日期: 2023-09-27 18:27:49
我想把一个mathod名称放入字符串中,但我也不想使用硬编码的值。相反,我想通过反思来动态地获得这个名字。我使用了以下工作语句:
"The method is called " + new Action(MyMethod).Method.Name;
我认为创建Action
委托在语义上是不合适的。这表明将有一个方法调用,但会有一个反射。我正在为类寻找typeof运算符或GetType之类的东西,但在方法级别。
模式Delegate.Method.Name
是否是实现我的目标的最佳和标准方法?
我的意思是而不是当前的方法。
MethodInfo.CurrentMethod应该为您提供当前方法的名称
"The method is called " + MethodInfo.GetCurrentMethod().Name;
使用MethodBase.GetCurrentMethod()
目前最好的解决方案:
-
创建静态类
ReflectionExtensionMethods
:public static class ReflectionExtensionMethods
-
添加
Action
、Action<T>
等、Func<T>
、Func<T1, T2>
等的几种方法。以下是Action
:的示例public static string GetMethodName(this Type @this, Expression<Action> expression) { return GetMethodNameInternal(@this, expression); }
-
检查给定表达式及其正文是否有效的内部部分:
private static string GetMethodNameInternal(Type @this, MethodCallExpression bodyExpression) { if (bodyExpression == null) throw new ArgumentException("Body of the exspression should be of type " + typeof(MethodCallExpression).Name); var member = bodyExpression.Method; if (member.MemberType != MemberTypes.Method) throw new ArgumentException("MemberType of the exspression should be of type " + MemberTypes.Method); if (!object.Equals(@this, member.DeclaringType)) throw new ArgumentException("Invalid property owner."); return member.Name; }
-
实例成员的用法:
var owner = new Foo(); var methodName = typeof(Foo).GetMethodName(() => owner.VoidMethod());
-
静态memeber的用法:
var methodName = typeof(Foo).GetMethodName(() => Foo.StaticVoidMethod());
CCD_ 9可以通过返回属性和其他成员的名称的方法来进一步补充。
这里是第一种方法。
-
创建一个名为MethodInfo的静态类(与System.Reflection.MethodInfo同名)。由于很少需要显式引用原始类型,因此可以推断出同名。然而,你自然会在那里寻找解决方案。
public static class MethodInfo { public static System.Reflection.MethodInfo From(Func<string, int> func) { return func.Method; } // Other members for Action<T>, Action<T1, T2> etc. // Other members for Func<T>, Func<T1, T2> etc. }
-
考虑有一个类MyClass,它有MyMethod方法:
class MyClass { static int MyMethod(string s) { return default(int); } }
-
使用类及其成员如下(关键部分):
"The method is called " + MethodInfo.From(MyClass.MyMethod).Name;
-
这比更具自我描述性、更易于使用和简洁
"The method is called " + new Func<string, int>(MyClass.MyMethod).Method.Name