1
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Test_console_application
{
    class Program
    {
        static void Main(string[] args)
        {
            var parentPropertyName = "Measurements";
            var parentPropertyType = typeof (Measurement);
            var propertyName = "Data";

            var parameterExp = Expression.Parameter(typeof(Inverter), "type");
            var propertyExp = Expression.Property(parameterExp, parentPropertyName);

            var method = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public)
                .Single(x => x.ToString() == "Double Min[TSource](System.Collections.Generic.IEnumerable`1[TSource], System.Func`2[TSource,System.Double])")
                .MakeGenericMethod(parentPropertyType);

            var minParameterExp = Expression.Parameter(parentPropertyType, "type2");
            var minPropertyExp = Expression.Property(minParameterExp, propertyName);
            var minMethodExp = Expression.Call(method, propertyExp, minPropertyExp);            
        }
    }

    public class Inverter
    {
        public IList<Measurement> Measurements { get; set; }
    }

    public class Measurement
    {
        public double Data { get; set; }
    }
}

当我运行此代码时,我得到一个 ArgumentException:

“System.Double”类型的表达式不能用于“System.Func 2[Test_console_application.Measurement,System.Double]' of method 'Double Min[Measurement](System.Collections.Generic.IEnumerable1[Test_console_application.Measurement]、System.Func`2[Test_console_application.Measurement,System.Double]) 类型的参数

我明白它的意思,但我只是认为我就是用 minPropertyExp 做的。
我不知道我需要改变什么——有什么线索吗?

4

1 回答 1

1

您不应将属性表达式作为 Func 传递。你应该传递一个方法。

你做了类似的事情:

Measurements.Min(type2.Data)

代替

Measurements.Min(x => x.Data)

来自 Morten Holmgaard 的评论

var minMethod = Expression.Lambda(minPropertyExp, minParameterExp);
var minMethodExp = Expression.Call(method, propertyExp, minMethod);
于 2012-10-30T13:21:42.587 回答