Create a generic collection of derived interfaces from a collection of base interfaces

一曲冷凌霜 提交于 2021-02-11 18:05:29

问题


I have a base interface

public interface IBase
{
    ...
}

and a interface that derives from this base

public interface IChild : IBase
{
    ...
}

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?


回答1:


You can't fill an ObservableCollection<IChild> with List<IBase>.

You can only fill an ObservableCollection<IBase> with List<IChild> because of inheritance theory rules.

Since IBase is a reduced version of IChild, types can't match: you can't convert IBase to IChild.

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:

What is inheritance

The wikipedia page about inheritance:

https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)




回答2:


Easies aproach for this would be having a constructor in your child class that takes in a IBase.

public interface IBase
{
}

public interface IChild : IBase
{
}

public class ChildClass : IChild
{
    public ChildClass(IBase baseClass) {
        // Do what needs to be done
    }
}

I hope I have understood your question right, as it is a little hard to get what exactly you are looking for.



来源:https://stackoverflow.com/questions/58133125/create-a-generic-collection-of-derived-interfaces-from-a-collection-of-base-inte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!