使用Linq调用是不明确的错误

首先,对于过分的通用名称类抱歉。 我的雇主是偏执狂,我肯定知道他漫游这个网站。 好的,所以我有这个代码:

var fooObj = new MyFooClass() { fooField1 = MyEnum.Value3, fooField2 = false, fooField3 = false, fooField4 = otherEntity.OneCollection.ElementAt(0) as MyBarClass } 

其他的Entity.OneCollection是一个ISet。 ISet是一个实现IEnumerable的NHibernate集合类。 如果我尝试编译此代码,我会收到此错误:

 Error 2 The call is ambiguous between the following methods or properties: 'System.Linq.Enumerable.ElementAt (System.Collections.Generic.IEnumerable, int)' and 'System.Linq.Enumerable.ElementAt(System.Collections.Generic.IEnumerable, int)' 

但是,如果我在类的开头删除使用System.Linq并将代码更改为:

 var fooObj = new MyFooClass() { fooField1 = MyEnum.Value3, fooField2 = false, fooField3 = false, fooField4 = System.Linq.Enumerable .ElementAt(otherEntity.OneCollection, 0) as MyBarClass } 

它编译和工作。 (?运算符检查OneCollection是否为了清晰起见而删除了元素)

任何人都可以向我解释这个错误吗?

如果相关:我正在使用Visual Studio 2008,目标是.NET Framework 3.5并使用ReSharper 5.1。

注意 – 编辑以澄清哪个具体的IEnumerable是集合,对不起。

这很奇怪。

该错误声称两个完全相同的签名之间存在歧义。

我唯一能想到的是,你可能会以某种方式将“引用”搞砸在你的项目中,也许你可以参考’System.Core 3.5’和’System.Core 3.5.0.1’(人为的例子) ..在这种情况下你会得到这样的错误,但是,我想不出为什么System.Linq.Enumerable.ElementAt(otherEntity.OneCollection工作 – 它应该报告同样的问题。

..或者你可能以某种邪恶的方式让你的’OneCollection’以两次方式实现IEnumerable? 但是,我认为错误信息会有所不同。

要删除含糊不清的引用,您必须更明确。 有两种选择。

首先,你可以使你的IEnumerable通用,如:

 IEnumerable = new List(); ... var fooObj = new MyFooClass() { fooField1 = MyEnum.Value3, fooField2 = false, fooField3 = false, fooField4 = otherEntity.OneCollection.ElementAt(0) as MyBarClass } 

或者第二; 如果它是非通用的IEnumerable,请进行强制转换:

 IEnumerable = new List(); ... var fooObj = new MyFooClass() { fooField1 = MyEnum.Value3, fooField2 = false, fooField3 = false, fooField4 = otherEntity.OneCollection.Cast().ElementAt(0) }