c# - 使用忽略重载的 lambda 语法选择方法表达式

标签 c# .net c#-3.0 lambda expression-trees

我目前使用以下扩展方法来选择方法:

    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/

相关文章:

c# - 为什么 Entity Framework 需要 30 秒来加载记录,而生成的查询只需要 1/2 秒?

c# - 遍历 2 个列表

c# - 为什么会出现序列化错误?

c# - 我可以在 WPF Canvas 中使用较低 ZIndex 的 HitTest 元素吗?

c# - c# 方法中的错误表示并非所有代码路径都返回一个值

c# - 使用 Postgres 和 C# 插入到哪里

c# - 从外部托管的应用程序和数据库导出数据

.net - 如何按应用程序名称过滤 Windows 事件查看器?(寻找我的 c#/wpf 崩溃)

.net - 什么时候应该使用 <%# ... %> 和 <%= ... %>?

c# - 我可以在同一类的另一个委托(delegate)中访问委托(delegate)吗?