我的代码具有3个(a,b,c)类,其中2(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=");// ı dont see myA.z
答案 0 :(得分:1)
自从您更新了很多问题以来,我已经删除了以前的答案。
之所以看不到该属性,是因为(如注释中所述),该列表仅包含一个“合同”以包含类A
的实例。即使它也包含派生的类(例如类B
),访问B
的属性仍然无效,因为我们只能“确定”列表中的元素包含至少A
的所有行为和属性。
这是设计使然,以确保我们在运行时不会意外尝试访问A
实例不存在的属性。