自定义配置部分,包含键和属性

时间:2016-12-23 00:16:12

标签: c# configuration web-config

我需要创建一个像appsettings这样的配置部分,但是周围的元素有一个属性,例如:

<userSettings>
    <machine name="my-machine">
        <setting key="Site" value="http://localhost" />
        <setting key="Online" value="true" />
    </machine>
    <!-- more machines -->
</userSettings>

根据示例,我有一组机器和设置集合正常工作,但我无法在机器上获取name属性以与设置集合一起使用。

这是我的机器类

public class Machine : ConfigurationElementCollection
{
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get
        {
            // This line doesn't compile, cannot convert SettingElement to string
            return (string)this["name"]; 
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new SettingElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((SettingElement)element).Key;
    }

    // this method is the problem but I want to be able to do 
    // something like 
    // section.Machines[Environment.MachineName][settingKey].Value
    public new SettingElement this[string index]
    {
        get { return (SettingElement)BaseGet(index); }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(BaseIndexOf(BaseGet(index)));
            }
            BaseAdd(value);
        }
    }
}

设置

public class SettingElement : ConfigurationElement
{
    [ConfigurationProperty("key", IsRequired = true, IsKey = true)]
    public string Key
    {
        get { return this["key"].ToString(); }
    }

    [ConfigurationProperty("value", IsRequired = true)]
    public string Value
    {
        get { return this["value"].ToString(); }
    }
}

0 个答案:

没有答案