开发者

List of abstract class

开发者 https://www.devze.com 2023-04-05 18:14 出处:网络
I have abstract class: pu开发者_如何学运维blic abstract class MyClass { public abstract string nazwa

I have abstract class:

pu开发者_如何学运维blic abstract class MyClass
{
    public abstract string nazwa
    {
        get;
    }
}

And two classes which inherit from MyClass:

public class MyClass1 : MyClass
{
    public override string nazwa
    {
        get { return "aaa"; }
    }
}

public class MyClass2 : MyClass
{
    public override string nazwa
    {
        get { return "bbb"; }
    }
}

In another class I create List:

List<MyClass> myList;

Now I want to create

myList = new List<MyClass1>;

The compiler show an error:

Cannot implicitly convert type 'System.Collections.Generic.List<Program.MyClass1>' to 'System.Collections.Generic.List<Program.MyClass>'

I must be some easy way to convert it... I cannot find anything useful


You can create the list as the base type:

List<MyClass> myList = new List<MyClass>();

Which you can then add derived items to:

myList.Add(new MyClass2());


It is not safe to convert a List<Derived> to a List<Base>.

What do you expect to happen if you write

List<MyClass1> derivedList = ...
List<MyClass> baseList = derivedList;
baseList.Add(new MyClass2());    //Boom!

You're asking for covariance; covariance is only possible with read-only interfaces.
Thus, IEnumerable<Derived> is convertible to IEnumerable<Base>.


You must have a base class list, and later you can use Linq to get the MyClas1 item list when you need it.

 List<MyClass> BaseList = new ...

 BaseList.FillWithItems();

 List<MyClass1> DerivedList = BaseList.OfType<MyClass1>().ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消