c# - 通过 Linq 表达式指定 MethodInfo 的面向 future 的方法

标签 c# linq reflection

我想要一种面向 future 的方式来通过 Linq 表达式指定方法。

我正在设计一个允许用户指定方法的 API。例如,客户端代码可能如下所示:ApiClass<ClientClass>.DoSomething(c => c.ClientMethod) .

我的 API 是强类型的。例如,

public void DoSomething(Expression<Func<TClientClass, Func<TParams, TResult>>> method){ ... }

我的问题:如何正确解析表达式树以获取客户端指定的 MethodInfo?

我一直在使用下面的代码,但似乎 .NET 4.5 的 4.5 版通过生成略有不同的表达式树来破坏它。我显然更愿意拥有适用于所有 future 版本的 C#/.NET 的东西

现有代码(类似于对 SO Extract method name from expression tree? 的回答):

private static MethodInfo GetMethodInfo(Expression method)
{
    var lambda = method as LambdaExpression;
    if (lambda == null) throw new ArgumentException("Argument is not a lambda expression (c => c.Thing)");
    var convert = lambda.Body;
    var body = (convert.NodeType == ExpressionType.Convert)
        ? ((UnaryExpression)convert).Operand as MethodCallExpression
        : convert as MethodCallExpression;
    if (body == null) throw new ArgumentException("Argument not in correct form (c => c.Thing)");
    var methodInfoValue = body
        .Arguments.OfType<ConstantExpression>()
        .Where(exp => exp.Type == typeof(MethodInfo))
        .Select(exp => (MethodInfo)exp.Value)
        .FirstOrDefault();
    if (methodInfoValue == null) throw new ArgumentException("Cannot find method name in expression.");
    return methodInfoValue;
}

(此代码在 .NET 4.5.1 上失败:以 null methodInfoValue 结尾。)

最佳答案

一个可能的解决方案似乎是使用 ExpressionVisitor 遍历 Expression 并查找值为 的任何 ConstantExpression >MethodInfo,其 MethodInfo.DeclaringType 属于正确的类......

这似乎适用于 .NET ≤ 4 和 .NET 4.5。

关于c# - 通过 Linq 表达式指定 MethodInfo 的面向 future 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23909101/

相关文章:

c# - 无法在 ASP.Net 和 C# 中使用 LINQ 解析 XML

c# - 在 Linq 中发出对象 where 子句 : the condition is bypassed

reflection - 在 F# 引号内嵌入变量

c++ - 实现反射 : How to find a parent of a class

c# - 使用 c# 作为 ul 列表而不是 Asp.net 菜单控件从数据表生成嵌套菜单

C# 我应该在连接池中保持打开连接吗

c# - .Net 中基于列的数据绑定(bind)?

c# - 在 Windows Phone 中以圆形显示图像

c# - .AsQueryable() 是否阻止 IEnumerable 将所有内容拉入内存?

java - 如何保留 lambda 的参数类型?