我目前使用以下扩展方法来选择方法:
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, Expression<Func<TType, 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)
{
}
}
关于c# - 使用忽略重载的 lambda 语法选择方法表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4377349/