類隊名單<Base> =名單<Derived>&法案喜歡清單<Derived>
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 Jill'沒有屬性'ClassRoom'它是一個列表... –
你如何期待'public'字段對派生類不可見? –
不,你不能讓人的行爲像老師,訪問屬性只屬於一個人對象上的老師將永遠不會工作.....我可能會重新考慮你的繼承在這裏......這是我認爲你不要使用繼承 –