无法为Custom ConfigurationElement类型的ConfigurationProperty设置DefaultValue

时间:2011-06-24 06:03:38

标签: c# .net configuration configurationelement

我对ConfigurationProperty的DefaultValue有一个小问题。

以下是我的XML配置的一部分:

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

要处理此配置,我创建了“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; }
    }
}

对于Type属性,我正在使用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; }
    }
}

问题是我无法为我的Type-property设置not-null DefaultValue。错误是:

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

我需要添加什么来启用默认值?

1 个答案:

答案 0 :(得分:4)

添加以下属性并检查是否为空。

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