1

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.Error に null 以外の DefaultValue を設定できないことです:

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

デフォルトを有効にするには、コードに何を追加する必要がありますか?

4

1 に答える 1

4

次の属性を追加して、nullを確認します。

[ConfigurationProperty("Type", DefaultValue="something")]
public string Type
{
    get
    {
        var tmp = base[TypePropertyName] as ConfigurationTextElement<string>;
        return tmp != null ? tmp.Value : "something";
    }
}
于 2011-06-24T06:19:07.353 に答える