简体   繁体   English

ConfigurationElement 设置空默认值

[英]ConfigurationElement set null default value

I have a small problem with a custom configuration section in App.config.我在 App.config 中的自定义配置部分有一个小问题。 The problem is: I have a CustomElement (let's call it 'a') whose properties CustomElement another (let's call it 'b').问题是:我有一个 CustomElement(我们称之为“a”),其属性 CustomElement 是另一个(我们称之为“b”)。

I would like to have b as a value not null only if specified as a secondary element.仅当指定为次要元素时,我才希望 b 作为值不为空。

Eg例如

In this case, I have ab as not null, and that's ok.在这种情况下,我有 ab 不为空,这没关系。

<a prop_a1="" prop_a2="">
    <B prop_b1 = "" />
</ A>

But, in the following case, b should be null, but it is not.但是,在以下情况下, b 应该为空,但事实并非如此。

<a prop_a1="" prop_a2="" />

Is it possible to have a null value in case 2?在情况 2 中是否可能有空值?

Thanks to all those who want to help me.感谢所有愿意帮助我的人。

public class Cfg : ConfigurationElement
{
        [ConfigurationProperty("prop", IsRequired = true)]
        public ErrorCfg Prop
        {
            get { return (string)this["prop"]; }
            set { this["prop"] = value; }
        }
}

public class ErrorCfg : ConfigurationElement
{
    [ConfigurationProperty("prop1", IsRequired = true)]
    public string Prop1
    {
        get { return (string)this["prop1"]; }
        set { this["prop1"] = value; }
    }

    [ConfigurationProperty("prop2", IsRequired = true)]
    public string Prop2
    {
        get { return (string)this["prop2"]; }
        set { this["prop2"] = value; }
    }
}

if (_cfgItem.ErrorCfg != null)
{....}

In this case ErrorCfg is not null, but Prop1 and Pro2 are empty string在这种情况下 ErrorCfg 不为空,但 Prop1 和 Pro2 为空字符串

I think this is not possible.我认为这是不可能的。 But you can find out if the ConfigurationElement is present in the configuration file:但是您可以查明配置文件中是否存在ConfigurationElement

if (_cfgItem.ErrorCfg.ElementInformation.IsPresent)
{....}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM