2013-04-08 60 views
5

首先,对于过分的通用名称类感到抱歉。我的雇主很偏执,我知道他肯定会漫游这个网站。好的,我有这样的代码:使用Linq调用不明确的错误

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

其中otherEntity.OneCollection是一个ISet。 ISet是实现IEnumerable的NHibernate集合类。如果我尝试编译这个代码,我得到这个错误:

Error 2  The call is ambiguous between the following methods or properties: 
'System.Linq.Enumerable.ElementAt<MyFirm.Blah.Blah.ClassyClass> (System.Collections.Generic.IEnumerable<MyFirm.Blah.Blah.ClassyClass>, int)' 
and 
'System.Linq.Enumerable.ElementAt<MyFirm.Blah.Blah.ClassyClass>(System.Collections.Generic.IEnumerable<MyFirm.Blah.Blah.ClassyClass>, 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是集合,对不起。

+0

您似乎已经引用了2个版本的'System.Linq.Enumerable ' – 2013-04-08 08:28:17

+0

您是否找到了解决方案?问题是什么?我真的好奇,因为这是相当罕见的问题 – quetzalcoatl 2013-04-16 09:09:01

+0

是的。我完全无法找到System.Linq.Enumerable的冗余引用,但是我能够继续做我在原始问题中提到的内容,而不是将ElementAt作为扩展方法调用,我将其称为使用它的常规方法完整的命名空间,即:System.Linq.Enumerable.ElementAt(集合,索引),而不是更好更可读的collection.ElementAt(索引)。 – CMPerez 2013-04-17 10:45:42

回答

1

要删除不明确的参考,您必须更加明确。有两种选择。

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

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

或第二;如果它是非泛型IEnumerable,请执行演员:

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

这是如何回答这个问题的?没有得到它..他说“Linq”功能由于模糊的呼叫而未被识别 – ephraim 2017-11-22 09:25:47

3

这很奇怪。

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

我唯一能想到的是,你可能会在你的项目中混淆'引用',也许你有'System.Core 3.5'和'System.Core 3.5.0.1'的引用, (人为的例子)..你会在这种情况下得到这样的错误,但是,我想不出为什么System.Linq.Enumerable.ElementAt(otherEntity.OneCollection工作 - 它应该报告相同的问题。

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