2009-04-22 81 views
2

我正在使用ResourceReader讀取嵌入式resx資源,並且希望將其存儲在類級別的成員變量中。我想將它作爲HybridDictionary存儲,但沒有看到一個簡單的方法。使用ResourceReader創建資源的HybridDictionary

initalize

Assembly asm = Assembly.GetExecutingAssembly(); 
Stream resourceStream = asm.GetManifestResourceStream("MagicBeans"); 

using (ResourceReader r = new ResourceReader(resourceStream)) 
{ 
    IEnumerable<DictionaryEntry> dictionary = r.OfType<DictionaryEntry>(); 
} 

屬性

public string Something { get { return dictionary["Something"].Value; }} 
public string ThatThing { get { return dictionary["ThatThing"].Value; }} 

然而,IEnumerable<DictionaryEntry>不工作我喜歡的方式和即時通訊目前在尋找做一些LINQ類成員

private IEnumerable<DictionaryEntry> dictionary; 

類'你喜歡; .First(x => x.Key=="Something").Value

回答

3

IEnumerable不支持key(字典[「something」]代碼中的部分)的訪問,以便您需要將字典屬性作爲IDictionary類訪問數據。喜歡的東西:

private IDictionary<string, object> dictionary; 

然後,你需要分析你從組件拉回數據來填充詞典:

Assembly asm = Assembly.GetExecutingAssembly(); 
Stream resourceStream = asm.GetManifestResourceStream("MagicBeans"); 

dictionary = new Dictionary<string, object>(); 

using (ResourceReader r = new ResourceReader(resourceStream)) 
{ 
    foreach(DictionaryEntry entry in r.OfType<DictionaryEntry>()) 
    { 
     dictionary.Add(entry.Key.ToString(), entry.Value); 
    } 
} 

最後的屬性將不再需要該值調用:

public string Something { get { return dictionary["Something"]; }} 
public string ThatThing { get { return dictionary["ThatThing"]; }} 

如果密鑰不存在於字典中,這些屬性將引發異常,因此您可能需要先檢查該屬性。

您的LINQ解決方案也應該可以工作,但是需要枚舉列表以查找每次請求屬性時正確的條目。

+0

+1。輝煌的第一個答案! – 2009-04-22 15:26:55

0

到資源轉換成一個字典,你可以使用以下命令:

using (var reader = new ResourceReader(resource)) 
{ 
    var dictionary = reader 
    .Cast<DictionaryEntry>() 
    .Aggregate(new Dictionary<string, object>(), (d, e) => { d.Add(e.Key.ToString(), e.Value); return d; }); 

    Console.WriteLine(dictionary["Foo"]); 
}