how do I find by key in ConfigurationElementCollection
我有一个从configurationElementCollection继承的类。我想添加一个名为findbykey的函数,它用一个特定的键返回configurationElement。键将是一个字符串,我知道配置元素将键存储为一个对象。
是否有人有任何简单的代码可以从键中检测元素?我确信一个简单的答案是基于了解configurationElementCollection属性并在字符串和对象之间快速转换。
谢谢J
我今天完成了一个示例,因为我正在为ConfigurationElementCollection类编写扩展。它可能不是非常理想的,但它有一个类似于您要求的包含键(key)的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public class ConfigurationElementCollectionExtension : ConfigurationElementCollection, IConfigurationElementCollectionExtension { protected override ConfigurationElement CreateNewElement() { throw new NotImplementedException(); } protected override object GetElementKey(ConfigurationElement element) { throw new NotImplementedException(); } bool IConfigurationElementCollectionExtension.ContainsKey<T>(T key) { bool returnValue = false; object[] keys = base.BaseGetAllKeys(); string keyValue = key.ToString(); int upperBound = keys.Length; List<string> items = new List<string>(); for (int i = 0; i < upperBound; i++) { items.Add(keys[i].ToString()); } int index = items.IndexOf(keyValue); if (index >= 0) { returnValue = true; } return returnValue; } } |
启动……外面有很多样品。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public class MYAppConfigTool { private Configuration _cfg; public Configuration GetConfig() { if (_cfg == null) { if (HostingEnvironment.IsHosted) // running inside asp.net ? { //yes so read web.config at hosting virtual path level _cfg = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath); } else { //no, se we are testing or running exe version admin tool for example, look for an APP.CONFIG file //var x = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; _cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); } } return _cfg; } public AppSettingsSection GetAppSettings() { var cfg = GetConfig(); return cfg == null ? null : cfg.AppSettings; } public string GetAppSetting(string key) { // null ref here means key missing. DUMP is good. ADD the missing key !!!! var cfg = GetConfig(); if (cfg == null) return null; var appSettings = cfg.AppSettings; return appSettings == null ? null : GetConfig().AppSettings.Settings[key].Value; } } |