开发者

Can't set DefaultValue for ConfigurationProperty of Custom ConfigurationElement type

开发者 https://www.devze.com 2023-03-15 15:08 出处:网络
I have a small problem with DefaultValue for ConfigurationProperty. Here is the part of my XML config :

I have a small problem with DefaultValue for ConfigurationProperty.

Here is the part of my XML config :

<Storage id="storageId">
    <Type>UNC</Type>
</Storage>

To process this config, I've created "StorageElement : ConfigurationElement" :

public class StorageElement : ConfigurationElement
{
    private static readonly ConfigurationPropertyCollection PropertyCollection = new ConfigurationPropertyCollection();

    internal const string IdPropertyName = "id";
    internal const string TypePropertyName = "Type";

    public StorageElement()
    {
        PropertyCollection.Add(
            new ConfigurationProperty(
                IdPropertyName, 
                typeof(string), 
                "", 
                ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey
                ));

        PropertyCollection.Add(
            new ConfigurationProperty(
                TypePropertyName,
                typeof(ConfigurationTextElement<string>),
                null,
                ConfigurationPropertyOptions.IsRequired));           
    }

    public string Id 
    { 
        get
        {
            return base[IdPropertyName] as string;
        }
    }

    public string Type
    {
        get
        {

            return (base[TypePropertyName] as ConfigurationTextElement<string>).Value;
        }
    }

    public override bool IsReadOnly()
    {
        return true;
    }

    protected override ConfigurationPropertyCollection Properties
    {
        get { return PropertyCollection; }
    }
}

For Type property , I'm using ConfigurationTextElement :

public class ConfigurationTextElement<T> : ConfigurationElement
{
    public override bool IsReadOnly()
    {
        return true;
    }

    private T _value;
    protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
    {
        _value = (T)reader.ReadElementContentAs(typeof(T), null);
    }

    public T Value
    {
        get { return _value; }
        set { _value = value; }
    }
}

Problem is that I can't set not-null开发者_如何转开发 DefaultValue for my Type-property.Error is :

An error occurred creating the configuration section handler for xxxConfigurationSection:
Object reference not set to an instance of an object.

What do I need to add to the code, to enable defaults?


Add the following attribute and check for null.

[ConfigurationProperty("Type", DefaultValue="something")]
public string Type
{
    get
    {
        var tmp = base[TypePropertyName] as ConfigurationTextElement<string>;
        return tmp != null ? tmp.Value : "something";
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消