2010-01-25 47 views
2

在解決方案中,我已經解決了這個問題=>General type conversion without risking Exceptions(請參閱問題底部的編輯),我需要緩存兩種類型之間轉換的方法。收集兩個鍵

因此,給定Type1和Type2我需要檢索一個方法。

在這個問題的答案=>What is the best C# collection with two keys and an object?建議使用詞典詞典。這與我所做的相似。

但我不喜歡它。它沒有邏輯上與集合意味着代表什麼。也要檢索一個值,我必須做的:

 if (!_Types.ContainsKey (s.GetType())) 
     { 
      type1Cache = new Dictionary<Type, ConversionCache>(); 

      _Types.Add (s.GetType(), type1Cache); 
     } 
     else 
     { 
      type1Cache = _Types[s.GetType()]; 
     } 

     if (!type1Cache.ContainsKey (value.GetType())) 
     { 
      // We havent converted this type before, so create a new conversion 
      type2Cache = new ConversionCache (s.GetType(), value.GetType()); 

      // Add to the cache 
      type1Cache.Add (value.GetType(), type2Cache); 
     } 
     else 
     { 
      type2Cache = type1Cache[value.GetType()]; 
     } 

這是一個有點長囉。

我只想做這樣的事情

 if (!_Types.ContainsKey (s.GetType(), value.GetType())) 
     { 
      cache = new ConversionCache (s.GetType(), value.GetType()); 

      _Types.Add (s.GetType(), value.GetType(), cache); 
     } 
     else 
     { 
      cache = _Types[s.GetType(), value.GetType()]; 
     } 

一個解決辦法是來串聯類型的字符串值。類似於:

 if (!_Types.ContainsKey (s.GetType().ToString() + ":" + value.GetType().ToString())) 
     { 
      cache = new ConversionCache (s.GetType(), value.GetType()); 
      _Types.Add (s.GetType().ToString() + ":" + value.GetType().ToString(), cache); 
     } 
     else 
     { 
      cache = _Types[s.GetType().ToString() + ":" + value.GetType().ToString()]; 
     } 

我知道它可以在此實例中工作,因爲在類型及其字符串表示之間存在一對一關係。

但是這種氣味很糟糕,並且在其他情況下不起作用。

有沒有更好的方法來做到這一點?

回答

1

你這樣做的方式很好。如果你想要一個更好的「嗅覺」系統,你只需要一個幫助函數,它接受兩個輸入(或類型)並返回一個唯一的字符串。然後,隱藏生成密鑰的實現細節(在這種情況下將它們與「:」分隔符連接起來)。

似乎有點過度工程給我。我不認爲有很多機會需要改變這種密鑰生成方法,並且你不想嘗試創建一個通用類。顯然你需要用一個通用類來完成。

2

您可能希望Tuples(在.Net 4中)或以前版本中的一個衆所周知的「Pair」類:KeyValuePair。

但是 - 考慮你的要求,我可能會去一個自定義類。你可以確保hashcode/equals做到了你想要的,可以覆蓋ToString()來進行合理的日誌記錄,並且它可能會讀得更好。