首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法为自定义ConfigurationElement类型的ConfigurationProperty设置DefaultValue

无法为自定义ConfigurationElement类型的ConfigurationProperty设置DefaultValue
EN

Stack Overflow用户
提问于 2011-06-24 14:03:38
回答 1查看 7K关注 0票数 1

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

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

代码语言:javascript
复制
<Storage id="storageId">
    <Type>UNC</Type>
</Storage>

为了处理这个配置,我创建了"StorageElement : ConfigurationElement“:

代码语言:javascript
复制
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; }
    }
}

对于类型属性,我使用ConfigurationTextElement:

代码语言:javascript
复制
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; }
    }
}

问题是我不能为我的类型属性设置非空的DefaultValue。错误是:

代码语言:javascript
复制
An error occurred creating the configuration section handler for xxxConfigurationSection:
Object reference not set to an instance of an object.

要启用默认值,我需要在代码中添加什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-06-24 14:19:07

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

代码语言:javascript
复制
[ConfigurationProperty("Type", DefaultValue="something")]
public string Type
{
    get
    {
        var tmp = base[TypePropertyName] as ConfigurationTextElement<string>;
        return tmp != null ? tmp.Value : "something";
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6464049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档