C# 编译器错误:表达式树可能不包含动态操作
考虑以下代码,它包装(而不是出于特定原因使用继承)了C# 编译器错误:表达式树可能不包含动态操作,c#,linq,dynamic,compiler-errors,expression-trees,C#,Linq,Dynamic,Compiler Errors,Expression Trees,考虑以下代码,它包装(而不是出于特定原因使用继承)了字典的一个实例,并实现了IEnumerable和IQueryable,以便可以与linq查询一起使用: public class LinqTest<T> : IEnumerable<KeyValuePair<string, T>>, IQueryable<KeyValuePair<string, T>> { private Dictionary<string, T>
字典的一个实例
,并实现了IEnumerable
和IQueryable
,以便可以与linq查询一起使用:
public class LinqTest<T> : IEnumerable<KeyValuePair<string, T>>, IQueryable<KeyValuePair<string, T>>
{
private Dictionary<string, T> items = default(Dictionary<string, T>);
public virtual T this[string key]
{
get { return this.items.ContainsKey(key) ? this.items[key] : default(T); }
set { this.items[key] = value; }
}
public virtual T this[int index]
{
get { return this[index.ToString()]; }
set { this[index.ToString()] = value; }
}
public Type ElementType
{
get { return this.items.AsQueryable().ElementType; }
}
public Expression Expression
{
get { return this.items.AsQueryable().Expression; }
}
public IQueryProvider Provider
{
get { return this.items.AsQueryable().Provider; }
}
public IEnumerator<KeyValuePair<string, T>> GetEnumerator()
{
return this.items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.items.GetEnumerator();
}
}
它编译、运行时没有任何错误,并且包含一个动态表达式……有人能解释一下,并可能指出我如何修复代码吗
注意:
.ForEach
是一种实现ForEach循环的非标准扩展方法。问题是您的类型实现了IQueryable
,因此Queryable
方法由成员查找选择-因此编译器尝试从lambda表达式创建表达式树。。。这就是失败的原因
字典示例之所以成功,是因为它使用的是Enumerable
而不是Queryable
,因此它将lambda表达式转换为委托
您可以使用AsEnumerable
修复代码:
item.AsEnumerable()
.Where(o => o.Value.GetType() == typeof(Guid))
.ForEach(i => Console.WriteLine(i));
老实说,您根本不清楚为什么要实现
IQueryable
——另一个更简单的选择就是停止这样做。您的源数据只是一个字典
,因此它已经将使用LINQ to对象,而不是任何基于可查询的对象。。。为什么要引入IQueryable
?您是否将其与Linq to Sql结合使用?或者只是Linq到对象?@Will,只是Linq到对象(暂时)“为什么要引入IQueryable”-因为我太傻了,没有研究IEnumerable和IQueryable之间的(巨大的和绝对的)差异,并且相信我的无知,Linq扩展只在实现IQueryable的对象上可用。非常感谢您的回答!:-)
Dictionary<string, dynamic> item = new Dictionary<string, dynamic>();
item["a"] = 45;
item["b"] = Guid.NewGuid();
item["c"] = "Hello World";
item["d"] = true;
item.Where(o => o.Value.GetType() == typeof(Guid)).ForEach(i => Console.WriteLine(i));
item.AsEnumerable()
.Where(o => o.Value.GetType() == typeof(Guid))
.ForEach(i => Console.WriteLine(i));