как мне найти по ключу в ConfigurationElementCollection

#c#

#c#

Вопрос:

У меня есть класс, который наследуется от ConfigurationElementCollection. Я хочу добавить функцию с именем FindByKey, которая возвращает ConfigurationElement с определенным ключом. Ключом будет строка, и я знаю, что ConfigurationElement хранит ключ как объект.

Есть ли у кого-нибудь какой-нибудь простой код для определения элемента по ключу? Я уверен, что простой ответ основан на знании свойств ConfigurationElementCollection и быстром преобразовании между string и object.

Спасибо J

Ответ №1:

У меня есть пример, который я завершил сегодня, поскольку я пишу расширение для класса ConfigurationElementCollection. Возможно, это не очень оптимально, но у него есть метод, аналогичный тому, о котором вы спрашиваете для containsKey (ключ).

 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;
        }
    }
  

Ответ №2:

Начало работы …. там много примеров.

 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;
    }
}