问题描述
我有一个基本界面
public interface IBase
{
...
}
和从此基础派生的接口
public interface IChild : IBase
{
...
}
在我的代码中,我调用一个方法,该方法将向我返回一个 List< IBase>
(旧版代码).使用此列表,我尝试填充 ObservableCollection< IChild>
:
Within my code, I call a method which will return me a List<IBase>
(legacy code). With this List I am trying to fill a ObservableCollection<IChild>
:
List<IBase> baseList= GetListofBase();
ChildList = new ObservableCollection<IChild>();
// how to fill ChildList with the contents of baseList here?
我知道不可能从基本类型转换为派生接口,但是可以从基本接口创建派生实例吗?
I know it is not possible to cast from a base to a derived interface, but is it possible to create a derived instance from a base interface?
推荐答案
您不能用 List< IBase>
填充 ObservableCollection< IChild>
.
由于继承理论的规定,您只能用 List< IChild>
填充 ObservableCollection< IBase>
.
You can only fill an ObservableCollection<IBase>
with List<IChild>
because of inheritance theory rules.
由于IBase是IChild的简化版本,因此类型不匹配:您无法将IBase转换为IChild.
Since IBase is a reduced version of IChild, types can't match: you can't convert IBase to IChild.
由于IChild是IBase的扩展版本,因此类型可以匹配:您可以将IChild转换为IBase.
Since IChild is an extended version of IBase, types can match: you can convert IChild to IBase.
例如,丰田汽车是汽车,但所有汽车都不是丰田,因此您可以像对待汽车一样对丰田行事,但不能像对待丰田那样对汽车行事,因为丰田汽车具有一些抽象汽车所没有的东西和可能性.
For example a Toyota car is a Car but all cars are not a Toyota, so you can act on a Toyota as if it is a Car, but you can't act on a Car as if it is a Toyota because a Toyota car have some things and possibilities that abstract Car have not.
检查一下本教程,这个概念对于类和接口都是相同的:
Check this tutorial about that, this concept is the same for classes as interfaces:
关于继承的维基百科页面:
The wikipedia page about inheritance:
https://en.wikipedia.org/wiki/Inheritance_(对象-定向编程)
这篇关于从基本接口集合创建派生接口的通用集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!