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:與LINQ最小方法構建表達式樹 - 引發的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])」
我明白我t說,但我只是認爲我是用minPropertyExp做的。
我不知道我需要改變什麼 - 任何線索?
但我怎麼然後創建這個方法 - 與反思? –
好吧,我解決了這個問題:var minMethod = Expression.Lambda(minPropertyExp,minParameterExp); \t \t \t VAR minMethodExp = Expression.Call(方法,propertyExp,minMethod);' –
@Morten:太好了,我不知道該怎麼做,但希望我的回答將幫助反正:-)增加您的解決方案到答案。 –