我不明白为什么编译器无法解析此处使用的正确重载。 (代码如下)只有一个版本的 Add() 是合适的 - BigFoo 是一个 IFoo,并且不实现 IEnumerable,其中 T 是一个 IFoo。但它坚持报告含糊之处。有任何想法吗?我尝试添加第二个泛型类型参数 - Add 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);
}
}
}
通用重载解析不考虑约束,因此它认为Add<T>
版本适用,推断T=int
.
两种方法都适用,并且没有绝对优于另一种的方法,因为两者之间没有转换IEnumerable<int>
and IFoo
。虽然泛型方法被认为比非泛型方法“不太具体”,但只有当类型参数替换后参数类型相同时,这才变得相关,而在本例中则不然。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)