【发布时间】:2017-03-23 14:55:29
【问题描述】:
类
public class Building
{
public string Name = "Not To Be Seen";
...
}
public class School: Building
{
public int NoOfRooms = 200;
public string Address = "123 Main St.";
...
}
目标(n 其他类/用例)
// This is a simple example, in reality this code is far more complex
// the class "School" is private from the program
List<Building> city = new List<School>();
// city will only have properties of the class School (or at least those are the only properties seen)
Console.WriteLine(city[0].NoOfRooms.ToString()) // Outputs 200
Console.WriteLine(city[0].Name) // Should not output anything
这似乎很有可能取决于正确转换列表。但是,我似乎无法弄清楚如何让它发挥作用。似乎它涉及协方差,但我确实不想要一个不可变的列表或类型。 C# 不是很容易提供这种转换吗(即基类可以完全模仿派生类)?
谢谢
【问题讨论】:
-
你的例子是错误的,
List<Person> Jill没有属性ClassRoom它是一个列表... -
您如何期望
public字段对派生类不可见? -
不,你不能让人表现得像老师,访问一个人对象上只属于老师的属性永远不会工作......我可能会在这里重新考虑你的继承......我认为你不使用继承
-
如果您不想让 Teach 看到 name 属性,您将不得不创建另一个继承 Person 的类。继承的类总是获取基类的所有属性。
-
Jill的类型是List<Person>,而不是Person,因此它既没有ClassRoom,也没有Name。第二:由于Teacherinherits 从Person它确实 有一个Name。所以有点不清楚你在问什么。第三:List<Teacher>不是List<Person>,所以它是不可分配的。即使在IList<T>接口中,T也是不变的,因为它既是输入值也是输出值。
标签: c# list class generics covariance