自定义ConfigurationSection默认布尔值

时间:2013-01-23 13:05:51

标签: c# .net

我创建了一个具有以下属性的自定义配置部分:

private const string UseMediaServerKey = "useMediaServer";
[ConfigurationProperty(UseMediaServerKey, IsRequired = false, DefaultValue = false)]
public bool UseMediaServer
{
    get { return bool.Parse(this[UseMediaServerKey] as string); }
    set { this[UseMediaServerKey] = value; }
}

我的理解是,如果配置文件中未定义属性,则应返回DefaultValue

但是,在上述情况下,ArgumentNullException会抛出bool.Parse(...),这意味着即使未定义配置属性,也会执行默认访问者。

当然我可以将属性访问者更改为:

    private const string UseMediaServerKey = "useMediaServer";
    [ConfigurationProperty(UseMediaServerKey, IsRequired = false)]
    public bool UseMediaServer
    {
        get {
            bool result;
            if (bool.TryParse(this[UseMediaServerKey] as string, out result))
            {
                return result;
            }

            return false;
        }
        set { this[UseMediaServerKey] = value; }
    }

但是,DefaultValue属性的重点是什么?

1 个答案:

答案 0 :(得分:8)

this[UseMediaServerKey] as stringnull,因为该值的类型为bool,而非string。您不必在自定义配置部分中进行任何字符串转换:框架将为您处理所有内容。

将您的代码简化为:

public bool UseMediaServer
{
    get { return (bool) this[UseMediaServerKey]; }
    set { this[UseMediaServerKey] = value; }
}

你已经完成了。如果配置文件中没有this[UserMediaServerKey],则DefaultValue将返回正确键入的TypeConverterAttribute。如果您不得不更改字符串转换过程,请在配置属性上放置{{1}}。但这不是必要的。