问题
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