无法从KeyValueConfigurationCollection转换为派生类

时间:2017-09-04 02:53:56

标签: c# configuration indexer

的值不存在时,尝试处理(内部)KeyValueConfigurationCollection例外,我有一个错误。

public class ConfigCore
{

    public static Configuration config 
    {
        get 
        {
             ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
             configFileMap.ExeConfigFilename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "App.config");
             return ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
        }
    }

    public static SettingsManager Settings
    {
        get
        {
            //config is an instance of System.Configuration.Configuration and works well.
            return (SettingsManager) config.AppSettings.Settings;
        }
    }

    internal static KeyValueConfigurationCollection Setts
    {
        get
        {
            return config.AppSettings.Settings;
        }
    }

    public static void CreateSettingEntry(string key, string value)
    {
        try
        {
            Setts.Add(key, value);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error ocurred trying to add value to Config. Message: {0}", ex.ToString());
        }
    }
}

public class SettingsManager : KeyValueConfigurationCollection
{
    public KeyValueConfigurationElement this[string key]
    {
        get
        {
            if (ConfigCore.Setts[key] == null)
                ConfigCore.CreateSettingEntry(key, "");
            return ConfigCore.Setts[key];
        }
    }
}

我想避免用户使用我的API执行以下操作:

if(ConfigCore.Settings["key"] == null)
    ConfigCore.CreateSettingEntry("key", "");

ConfigCore.Settings["key"].Value = "value";

由于这个原因,我创建了一个内部索引器来搜索这种情况,并在设置之前自动调用创建条目的方法。

但由于某种原因,发生了一个异常,说KeyValueConfigurationCollection无法转换为SettingsManager,为什么如果SettingsManager是KeyValueConfigurationCollection的继承类,我忘记了什么?

提前致谢!

1 个答案:

答案 0 :(得分:1)

我今天一直在研究这个问题。

public static class KeyValueConfigurationCollectionExtension 
    {
        public static bool ContainsKey<T>(T key)
        {
            System.Collections.Specialized.NameValueCollection coll = new System.Collections.Specialized.NameValueCollection();

            string keyValue = key.ToString();
            int upperBound = coll.Count;
            List<string> items = new List<string>();
            for(int i = 0; i < upperBound; i++)
            {
                items.Add(coll[i].ToString());
            }

            int index = items.IndexOf(keyValue);
            if(index >= 0)
                return true;

            return false;

        }
    }