2016-07-01 56 views
-1

我想創建一個場景或狀態管理器,它爲每個狀態存儲一個字典作爲加載或更改程序狀態的一種方式(例如,主菜單狀態和遊戲狀態)。我有一堆基類State的派生類,它們的變量不包含在基類State中。我能否安全地將它們存儲在本詞典中?我會有任何數據丟失嗎?如果這不起作用,有什麼替代方法來實現我的目標?在派生類中存儲派生類字典

回答

1

這似乎是你可以輕鬆測試自己的東西。但只是爲了好玩,假設你有一個基類,如:

public class Base 
{ 
    public string Name 
    { 
     get; 
     set; 
    } 

    public override string ToString() 
    { 
     return Name; 
    } 
} 

而派生類,如:

public class Derived : Base 
{ 
    public string Description 
    { 
     get; 
     set; 
    } 

    public override string ToString() 
    { 
     return base.ToString() + " - " + Description; 
    } 
} 

然後你就可以創建一個設置是這樣的:

Base baseObject = new Base{ Name = "Base"}; 
Derived derivedObject = new Derived { Name = "Derived", Description = "Description" }; 

Dictionary<int, Base> dictionary = new Dictionary<int, Base>(); 
dictionary.Add(1, baseObject); 
dictionary.Add(2, derivedObject); 

現在您可以運行一下測試,看看是否有任何信息丟失:

foreach (Base value in dictionary.Values) 
{ 
    Console.WriteLine(value.ToString()); 
} 

正如你所看到的,不僅調用了正確的被覆蓋的ToString(),而且它還具有Description屬性的正確值。所以不,你不會「失去」任何東西。但只要它是base類型,您就只能直接訪問base屬性。

Btw。你也可以檢查,如果值確實is一定的派生類型:

foreach (Base value in dictionary.Values) 
{ 
    if (value is Derived) 
    { 
     Console.WriteLine("{0} is Derived", value.Name); 
     // trying to access value.Description at this point 
     // would cause a compiler error "Cannot resolve symbol". 
    } 
    else 
    { 
     Console.WriteLine("{0} is not Derived", value.Name); 
    } 
} 

而且隨着as和空支票,你可以「安全地」(即沒有造成直接鑄造例如除外)獲得的價值在「完整」派生類型中,您可以再次訪問所有附加屬性:

foreach (Base value in dictionary.Values) 
{ 
    Derived derived = value as Derived; 
    if (derived != null) 
    { 
     Console.WriteLine("{0} is Derived and has Description: {1}", 
          derived.Name, derived.Description); 
     // now that derived actually is of type Derived, 
     // accessing derived.Description is perfectly fine. 
    } 
}