如何继承基础对象的List <>作为派生对象的List <>?

时间:2019-03-28 18:04:37

标签: c# list inheritance

是否可以继承基础对象列表作为派生对象列表?不知道如何更好地解释它。希望这个例子可以清楚地说明:

public abstract class MyBase
{ }

public class MyConcrete: MyBase
{ }

public abstract class MyBases: IList<MyBase>
{
    internal abstract List<MyBase> Items { get; set; }
    public MyBase this[int index] { get => ((IList<MyBase>)Items)[index]; set => ((IList<MyBase>)Items)[index] = value; }

    // other implementations of IList...
}

public class MyConcretes: MyBases
{
    //Possible:
    internal override List<MyBase> Items { get; set; }

    // Needed
    internal override List<MyConcrete> Items { get; set; }
}

1 个答案:

答案 0 :(得分:1)

您可以使用模板类。

public abstract class MyBases<T> : IList<T>
{
    internal abstract List<T> Items { get; set; }
    public MyBase this[int index] { get => ((IList<MyBase>)Items)[index]; set => ((IList<MyBase>)Items)[index] = value; }

    // other implementations of IList...
}

public class MyConcretes : MyBases<MyConcrete>
{
    internal override List<MyConcrete> Items { get; set; }
}