gpt4 book ai didi

c# - 编译器错误 : An expression tree may not contain a dynamic operation

转载 作者:太空狗 更新时间:2023-10-29 22:58:32 27 4
gpt4 key购买 nike

考虑以下代码,它包装(而不是出于特定原因使用继承) Dictionary<string, T> 的一个实例并实现 IEnumerableIQueryable以便它可以与 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();
}
}

我测试了这段代码如下:

LinqTest<dynamic> item = new LinqTest<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));

//Compiler error: An expression tree may not contain a dynamic operation

这向我表明 o.Value.GetType() == typeof(Guid)无法编译到表达式中,因为它是 dynamic .

但是,我用下面的代码测试了这个理论:

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));

这可以编译和运行,没有任何错误,并且包含一个动态表达式...任何人都可以解释,并可能指出我如何修复我的代码吗?

注意: .ForEach是实现 foreach 循环的非标准扩展方法。

最佳答案

问题是你的类型实现了IQueryable<> , 所以 Queryable方法由成员查找选择 - 因此编译器会尝试从您的 lambda 表达式创建一个表达式树……这就是失败的原因。

字典示例成功,因为它使用了 Enumerable而不是 Queryable ,因此它将 lambda 表达式转换为委托(delegate)。

您可以使用 AsEnumerable 修复您的代码:

item.AsEnumerable()
.Where(o => o.Value.GetType() == typeof(Guid))
.ForEach(i => Console.WriteLine(i));

不清楚您为什么要实现 IQueryable<>老实说——另一个更简单的选择就是停止这样做。您的源数据只是一个 Dictionary ,所以这已经将使用 LINQ to Objects 而不是任何基于可查询的东西......为什么要介绍 IQueryable<>有没有?

关于c# - 编译器错误 : An expression tree may not contain a dynamic operation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27486870/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com