我在C#中遇到多态性问题。我有一个实现接口的对象,但是我不能将对象的集合表示为接口的集合。面对我对多态性的理解,这真是天壤之别。所以我想知道哪里出了问题。
[TestFixture]
class Tester
{
[Test]
public void Polymorphism()
{
var list = new List<Foo> {new Foo {Name = "Item"}};
Assert.That(list, Is.InstanceOf<IList>());
Assert.That(list[0], Is.InstanceOf<Foo>());
Assert.That(list[0], Is.InstanceOf<IBar>());
// why are the rest true but this false?
Assert.That(list, Is.InstanceOf<IList<IBar>>());
}
}
internal interface IBar
{
}
internal class Foo : IBar
{
public string Name { get; set; }
}
这是一个方差问题,而不是多态性。
如果Foo列表也是IBar的IList,则可以进行以下操作:
class Another : IBar {}
IList<IBar> list = new List<Foo>();
list.Add(new Another());
然后,我们将另一个添加到Foo列表中。这是一个错误。编译器阻止您犯错。
请注意,最新的编译器/.net版本通过“ in” /“ out”支持差异。因此,作为IBar的IEnumerable-IBar可以很好地使用List-of-Foo。因为保证只返回Foo(不接受它们),并且所有Foo都是IBar,所以很安全。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句