我不明白为什么编译器无法解决要在此处使用的正确重载。(下面的代码)只有一个版本的 Add() 是合适的——BigFoo 是一个 IFoo,并且不实现 IEnumerable,其中 T 是一个 IFoo。但它坚持报告模棱两可。有任何想法吗?我尝试添加第二个泛型类型参数 - 添加 where T : IFoo where U : IEnumerable。但是即使合法使用,过载也会被完全忽略。
我知道我可以通过强制转换和指定泛型类型参数来解决这个问题,但那时我已经打败了重载的目的。您可能会质疑重载,但语义对我来说是正确的——我在课堂上实现的行为是让 Add() 都将对象批发添加为集合中的单个条目。(第二个 Add() 不应该是 AddRange()。)
namespace NS
{
interface IFoo { }
class BigFoo : IFoo, IEnumerable<int>
{
public IEnumerator<int> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
class FooContainer
{
public void Add(IFoo item) { }
public void Add<T>(IEnumerable<T> group) where T : IFoo { }
}
class DemoClass
{
void DemoMethod()
{
BigFoo bigFoo = new BigFoo();
FooContainer fooContainer = new FooContainer();
// error CS0121: The call is ambiguous between the following methods or properties:
// 'NS.FooContainer.Add(NS.IFoo)' and
// 'NS.FooContainer.Add<int>(System.Collections.Generic.IEnumerable<int>)'
fooContainer.Add(bigFoo);
}
}
}