[英]how do I find by key in ConfigurationElementCollection
I have a class which inherits from ConfigurationElementCollection. 我有一个继承自ConfigurationElementCollection的类。 I want to add a function called FindByKey which returns the ConfigurationElement with a specific key. 我想添加一个名为FindByKey的函数,该函数返回带有特定键的ConfigurationElement。 The key will be a string and I know that the ConfigurationElement stores the key as an object. 密钥将是一个字符串,我知道ConfigurationElement将密钥存储为一个对象。
Does anyone have any simple code to detect the element from the key? 有没有人有任何简单的代码来检测密钥中的元素? I am sure that a simple answer is based on knowing the ConfigurationElementCollection properties and quickly converting between string and object. 我确信一个简单的答案是基于了解ConfigurationElementCollection属性并在字符串和对象之间快速转换。
Thanks J 谢谢J
I have an example I completed today, as I am writing an extension for the ConfigurationElementCollection class. 我有一个今天完成的示例,因为我正在编写ConfigurationElementCollection类的扩展。 It may not be very optimal, but it has a similar method to the one you're asking about for ContainsKey(key). 它可能不是最佳选择,但是它具有与您要的ContainsKey(key)类似的方法。
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;
}
}
Kick start.... many samples out there. 开始...。那里有很多样品。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.