gpt4 book ai didi

c# - 无法为自定义 ConfigurationElement 类型的 ConfigurationProperty 设置 DefaultValue

转载 作者:太空宇宙 更新时间:2023-11-03 22:11:30 25 4
gpt4 key购买 nike

我对 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; }
}
}

问题是我无法为我的类型属性设置非空默认值。错误是:

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

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

最佳答案

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

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

关于c# - 无法为自定义 ConfigurationElement 类型的 ConfigurationProperty 设置 DefaultValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6464049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com