简体   繁体   English

检索字典 <string, int> 使用DictionarySectionHandler从app.config中获取

[英]Retrieving Dictionary<string, int> from app.config using DictionarySectionHandler

I am trying to store a Dictionary in app.config. 我正在尝试将字典存储在app.config中。 It would be very useful to avoid having to parse each string by while using NameValueCollectionSectionHandler, so I was looking instead at DictionarySectionHandler. 避免在使用NameValueCollectionSectionHandler时必须解析每个字符串,这将非常有用,因此我正在查看DictionarySectionHandler。

I have been able to import a Hashtable, but it seems I can only get string values. 我已经能够导入哈希表,但似乎只能获取字符串值。 Is there a way to get to a Dictionary directly without parsing everything? 有没有一种方法可以直接获取字典而无需解析所有内容?

Is there anyway to import a Dictionary directly? 无论如何有直接导入字典吗? I cannot seem to get DictionarySectionHandler to give me an actual Dictionary. 我似乎无法让DictionarySectionHandler给我一个实际的字典。

DictionarySectionHandler will always return an HashTable DictionarySectionHandler将始终返回一个HashTable

You just have to transform it to a Dictionary using the types that you want 您只需要使用所需的类型将其转换为Dictionary

For examples if your Dictionary values are integer you could do 例如,如果您的Dictionary值为整数,则可以执行

Dictionary<string,int> targetDictionary = sourceHashtable.Cast<DictionaryEntry>().ToDictionary(d => (string)d.Key, d => (int)d.Value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM