简体   繁体   中英

Add lists to another list class

My code has 3 classes (a, b, c), that (b,c) classes inherit a. and I have a list (list mylist). My prblem is about adding to element from class b or class 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 
    }
}

I've removed my former answer since you updated the question a lot.

The reason you don't see the property is because (as mentioned in a comment), the list only contains a "contract" to contain instances of the class A . Even if it also containes derrived classes (such as class B ), it still isn't valid to access properties of B , because we can only ever be "certain" that the elements inside the list contain at least all the behavior and properties of A .

This is by design to ensure that we can't accidentally try accessing a property which doesn't exist for an instance of A during runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM