2012-07-24 80 views
1

是否有办法编写一些ConfigurationValidatorAttribute或以其他方式允许Prop1Prop2都存在或不存在?如何检查配置元素中是否存在这两个属性或其中没有一个属性?

EDITED

在下面的配置文件时,我会尽量让Domains我想运行例外,因为domain3元素必须同时Prop1Prop2或没有人,但不是唯一的一个他们!

就像IsRequired在运行时检查,如果该元素没有Name属性,则会抛出错误。

<MySection> 
     <Domains> 
      <Domain Name="domain1" Prop1="1" Prop2="4" /> 
      <Domain Name="domain2" /> 
      <Domain Name="domain3" Prop1="1" /> 
     </Domains>   
    </MySection> 

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

    [ConfigurationProperty("Prop1")] 
    public int Prop1 
    { 
     get { return (int)this["Prop1"]; } 
     set { this["Prop1"] = value; } 
    } 

    [ConfigurationProperty("Prop2")] 
    public int Prop2 
    { 
     get { return (int)this["Prop2"]; } 
     set { this["Prop2"] = value; } 
    } 
} 
+0

如果验证失败,您希望的行为是什么?运行时异常? – 2012-07-24 16:32:43

+0

我不认为你可以得到一个编译错误,因为app.config总是可以在稍后阶段改变。但您可以添加xsd验证,请参阅http://stackoverflow.com/questions/334473/providing-intellisense-xsd-validation-to-configsections。 – Maarten 2012-07-24 17:55:36

+0

@dtryon,我编辑了我的帖子。是的,我希望运行时异常类似于'IsRequeired',例如,抛出excelpion – theateist 2012-07-25 08:10:45

回答

2

覆盖的ConfigurationElementPostDeserializeConfigElement

protected override void PostDeserialize() 
     { 
      base.PostDeserialize(); 
      //Do what you want 
     } 

有一个很好的例子on this blog post

+0

这正是我所期待的。谢谢! – theateist 2012-07-25 09:07:38

+0

这与ElementInformation.IsPresent结合使用,如果您希望您的“它不存在默认值”与“您的默认值”有所不同,也是有用的。 – 2016-05-11 01:20:35

相关问题