我正在尝试提取Count方法,所以我可以在以后重用它来构建表达式树。
var g = Expression.Parameter(typeof(IEnumerable<float?>), "g");
var countMethod = typeof(Enumerable)
.GetMethods()
.Single(m => m.Name == "Count" && m.GetParameters().Count() == 1);
var countMaterialized = countMethod
.MakeGenericMethod(new[] { g.Type });
var expr = Expression.Call(countMaterialized, g);
它抛出此错误:
System.ArgumentException:'类型'的表达式System.Collections.Generic.IEnumerable1[System.Nullable
1 [System.Single]]'不能用于'System.Collections.Generic.IEnumerable1[System.Collections.Generic.IEnumerable
1 [System.Nullable1[System.Single]]]' of method 'Int32 Count[IEnumerable1](System.Collections.Generic.IEnumerable
1 [System.Collections.Generic.IEnumerable1[System.Nullable
1]类型的参数[System.Single]]])'
我错过了什么?
您的参数类型是正确的,但您的泛型类型应该是“浮动”?而不是“IEnumerable”。
var g = Expression.Parameter(typeof(IEnumerable<float?>), "g");
// get the method definition using object as a placeholder parameter
var countMethodOfObject = ((Func<IEnumerable<object>, int>)Enumerable.Count<object>).Method;
// get the generic method definition
var countMethod = countMethodOfObject.GetGenericMethodDefinition();
// create generic method
var countMaterialized = countMethod.MakeGenericMethod(new[] { typeof(float?) });
// creare expression
var countExpression = Expression.Call(countMaterialized, g);
var expression = Expression.Lambda<Func<IEnumerable<float?>, int>>(countExpression, g);
IEnumerable<float?> floats = Enumerable.Range(3, 5).Select(v => (float?)v);
var count = expression.Compile().Invoke(floats);