簡體   English   中英

將列表添加到另一個列表類

[英]Add lists to another list class

我的代碼有3個類(a,b,c),該(b,c)類繼承了a。 並且我有一個列表(列出我的列表)。 我的問題是關於添加到b類或c類的元素

public class A
{
    public int x;
    public int y;
    public A(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

public class B : A
{
    public int z;
    public B(int x, int y, int z) : base(x, y)
    {

    }
}

class Program
{
    static void Main(string[] args)
    {
        var myA = new List<A>();
        myA.Add(new A(1, 2));
        myA.Add(new B(3, 4, 5));
        Console.WriteLine(myA[1]); 
        Console.WriteLine("0.x=" + myA[0].x + "--0.y=" + myA[0].y);
        Console.WriteLine("1.x=" + myA[1].x + "--1.y=" + myA[1].y + "--1.z=");// I can't see myA.z 
    }
}

自您更新了很多問題以來,我已經刪除了以前的答案。

您看不到該屬性的原因是(如注釋中所述),該列表僅包含一個“合同”以包含類A實例。 即使它也包含派生的類(例如B ),訪問B屬性仍然無效,因為我們只能“確定”列表中的元素至少包含B的所有行為和屬性。 A

這是設計使然,以確保我們在運行時不會偶然嘗試訪問A實例不存在的屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM