【发布时间】:2015-09-12 20:37:32
【问题描述】:
我正在研究“表达式树”,但我无法执行这些表达式:
// first case
someList.Select(p => p.SomeProperty);
和
// second case
someList.Select(p => new OtherClass
{
SomeProperty = p.SomeProperty
})
对于我尝试这样做的“第一种情况”:
var someList = new List<SomeClass>();
someList.Add(new SomeClass { SomeProperty = "Hello" });
var someParam = Expression.Parameter(typeof(SomeClass), "p");
var someProperty = Expression.Property(someParam, "SomeProperty");
Expression.Call(
typeof(Enumerable),
"Select",
new Type[]
{
typeof(SomeClass),
typeof(string)
},
Expression.Lambda(
someProperty,
someParam
)
).Dump();
但我收到此错误:
InvalidOperationException:类型“System.Linq.Enumerable”上没有通用方法“Select”与提供的类型参数和参数兼容。如果方法是非泛型的,则不应提供类型参数。
关于“第二种情况”,我不知道如何进行。
有人可以在这里指导我吗?
【问题讨论】:
-
我认为您缺少在
Expression.Call中提供介于new Type[]和Expression.Lambda之间的 IEnumerable参数 -
您不能直接使用带有
Enumerable.*方法的表达式树。你必须.Compile()他们,或者使用IQueryable<>和Queryable.*方法。
标签: c# lambda expression expression-trees enumerable