c# – 使用忽略重载的lambda语法选择方法表达式
发布时间:2020-12-15 21:13:09 所属栏目:百科 来源:网络整理
导读:我目前使用以下扩展方法来选择方法: public static MethodInfo GetMethodTType(this TType type,ExpressionActionTType methodSelector) where TType : class { return ((MethodCallExpression)methodSelector.Body).Method; } 这被称为: this.GetMethod(x
我目前使用以下扩展方法来选择方法:
public static MethodInfo GetMethod<TType>(this TType type,Expression<Action<TType>> methodSelector) where TType : class { return ((MethodCallExpression)methodSelector.Body).Method; } 这被称为: this.GetMethod(x => x.MyMethod(null,null)) 对我来说,选择哪种方法并不重要,我只是使用它作为以强类型方式获取方法名称的方法.有没有办法我仍然可以使用lambda语法选择方法但不指定任何参数? 即 this.GetMethod(x => x.MyMethod) 解决方法
这似乎有效,但增加了必须为采用参数的方法指定签名的成本.我无法弄清楚如何自动获取这些.
public static class ObjectExtensions { public static MethodInfo GetMethod<TType,TSignature>(this TType type,Expression<Func<TType,TSignature>> methodSelector) where TType : class { var argument = ((MethodCallExpression)((UnaryExpression)methodSelector.Body).Operand).Arguments[2]; return ((ConstantExpression)argument).Value as MethodInfo; } public static MethodInfo GetMethod<TType>(this TType type,Action>> methodSelector) where TType : class { return GetMethod<TType,Action>(type,methodSelector); } } 测试了这个简单的例子: public class MyClass { public static void RunTest() { var m = new MyClass().GetMethod(x => x.Test); Console.WriteLine("{0}",m); m = new MyClass().GetMethod<MyClass,Action<int>>(x => x.Test2); System.Console.WriteLine("{0}",m); Console.ReadKey(); } public void Test() { } public void Test2(int a) { } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |