是否有办法编写一些ConfigurationValidatorAttribute
或以其他方式允许Prop1
和Prop2
都存在或不存在?如何检查配置元素中是否存在这两个属性或其中没有一个属性?
EDITED
在下面的配置文件时,我会尽量让Domains
我想运行例外,因为domain3
元素必须同时Prop1
和Prop2
或没有人,但不是唯一的一个他们!
就像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; }
}
}
如果验证失败,您希望的行为是什么?运行时异常? – 2012-07-24 16:32:43
我不认为你可以得到一个编译错误,因为app.config总是可以在稍后阶段改变。但您可以添加xsd验证,请参阅http://stackoverflow.com/questions/334473/providing-intellisense-xsd-validation-to-configsections。 – Maarten 2012-07-24 17:55:36
@dtryon,我编辑了我的帖子。是的,我希望运行时异常类似于'IsRequeired',例如,抛出excelpion – theateist 2012-07-25 08:10:45