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.IEnumerable
1[Test_console_application.Measurement]、System.Func`2[Test_console_application.Measurement,System.Double]) 类型的参数
我明白它的意思,但我只是认为我就是用 minPropertyExp 做的。
我不知道我需要改变什么——有什么线索吗?