我有一種情況,我想創建一個可以容納父類和子類型的字典。我想存儲不同的孩子類型,並能夠調用他們的數據。從存儲父類類型的字典訪問子屬性
我正在運行的問題是,當將對象拉出字典時,它們被視爲它們的父類型,因爲字典類型被設置爲父對象。我想通過使用var實例化一個新對象(參見下文),我已經想出了訪問其附加屬性的唯一方法。
任何幫助將不勝感激。另外,如果我的行話/術語不正確,請隨時糾正我正在嘗試學習的內容。謝謝!
更新:我稍微更新了我的代碼,以嘗試傳達我正在嘗試執行的操作。 (添加了foreach循環)。
public class parent
{
public string name;
}
public class child : parent
{
public int age;
}
public class library
{
}
public class Program
{
public static void Main(string[] args)
{
Dictionary<int, parent> dictionary = new Dictionary<int, parent>();
child child1 = new child();
child child2 = new child();
child1.age = 5;
child2.age = 10;
dictionary.Add(1,child1);
dictionary.Add(2,child2);
foreach(KeyValuePair<int, parent> d in dictionary)
{
Console.WriteLine(d.age);
}
}
}
即使您的代碼顯示了所涉及的對象和類型,它實際上也不會顯示您遇到的問題。展示代表您問題的最少量代碼是適當的禮節。 – Enigmativity 2014-12-11 00:22:15