动态+ linq编译错误
我会在前面说我在动态数据上使用linq做了一些非常可怕的事情。 但我无法弄清楚为什么这个查询无法编译:
错误1属性’ h__TransparentIdentifier0’不能与类型参数一起使用
公共课程 { public static void Main(string [] args) { var docs = new dynamic [0]; var q =来自docs中的doc doc [“@ metadata”] [“Raven-Entity-Name”] ==“Cases” doc.AssociatedEntities!= null 来自doc.AssociatedEntities中的实体 其中entity.Tags!= null //编译器错误在这里 来自entity.Tags中的标签 其中tag.ReferencedAggregate!= null 选择新的{tag.ReferencedAggregate.Id,doc .__ document_id}; } } 公共静态类LinqOnDynamic { private static IEnumerable 选择(此对象为self) { if(self == null) 产量突破; if(self是IEnumerable == false || self是string) 抛出新的InvalidOperationException(“试图枚举”+ self.GetType()。Name); foreach(((IEnumerable)self中的var项目)) { 收益率项目; } } public static IEnumerable SelectMany(this object source, Func <dynamic,int,IEnumerable > collectionSelector, Func resultSelector) { return Enumerable.SelectMany(Select(source),collectionSelector,resultSelector); } public static IEnumerable SelectMany(this object source, Func <dynamic,IEnumerable > collectionSelector, Func resultSelector) { return Enumerable.SelectMany(Select(source),collectionSelector,resultSelector); } public static IEnumerable SelectMany(this object source, Func <object,IEnumerable > selector) { return Select(source).SelectMany (selector); } public static IEnumerable SelectMany(this object source, Func <object,int,IEnumerable > selector) { return Select(source).SelectMany (selector); } }
为了增加对伤害的侮辱,以下工作:
var docs = new dynamic [0]; var q =来自docs中的doc doc [“@ metadata”] [“Raven-Entity-Name”] ==“Cases” doc.AssociatedEntities!= null 来自doc.AssociatedEntities中的实体 其中entity.Tags!= null 来自entity.Tags中的标签 选择新的{tag.ReferencedAggregate.Id,doc .__ document_id};
只有当我添加:
其中tag.ReferencedAggregate!= null
我之前收到两行错误:
其中entity.Tags!= null //编译器错误在这里
不知道发生了什么
如果我尝试将您的通话转换为:
var q = from doc in docs.Where(doc => doc["@metadata"]["Raven-Entity-Name"] == "Cases" || doc.AssociatedEntities != null) from entity in doc.AssociatedEntities.Where(entity => entity.Tags != null)
我得到一个不同的编译器错误,可能会揭示正在发生的事情:
‘不能先将lambda表达式用作动态调度操作的参数,而不先将其转换为委托或表达式树类型’
所以我猜你必须重载Where运算符。
var q =来自docs中的doc doc [“@ metadata”] [“Raven-Entity-Name”] ==“Cases” doc.AssociatedEntities!= null 来自实体 ((IEnumerable的<动态>)doc.AssociatedEntities) .Where(entity => entity.Tags!= null) 来自标签 ((IEnumerable的<动态>)entity.Tags) .Where(tag => tag.ReferencedAggregate!= null) 选择新的{tag.ReferencedAggregate.Id,doc .__ document_id};
那更好一点。 不完美,但它就像开始一样 – 你只能在陷入困境之前走得那么深。
匿名类型返回是<> h__TransparentIdentifier0并且在编译时由编译器处理 – 问题显示为“动态优先顺序” – 请在此处阅读: C#4.0中缺少方法的方法:动态与RealProxy
我今天刚刚完成了这篇文章。 我将有一个小猜测,并说动态分配后准备匿名类型:) – 编译器知道这一点,并挫败你。
如果使用常规类型返回,问题是否会消失? 我猜它必须。