C# 针对多个值的自定义.NET ConfigurationSection验证
我正在实现一个自定义的.NETC# 针对多个值的自定义.NET ConfigurationSection验证,c#,validation,config,C#,Validation,Config,我正在实现一个自定义的.NETConfigurationSection,需要验证配置中是否满足两个条件之一,但我不确定如何针对多个字段进行验证 基本上,条件是,给定三个KVP(A、B和C),要么需要A,要么需要B和C 因为它们实际上是独立可选的,所以我不能将它们标记为必需的,但是有效配置需要两个条件之一 我读过关于在Jon Rista上编写自定义验证器的文章,但这些只验证单个字段的值 我是否应该将这三个设置嵌套为它们自己的ConfigurationElement,并为公开此部分的属性编写一个验证
ConfigurationSection
,需要验证配置中是否满足两个条件之一,但我不确定如何针对多个字段进行验证
基本上,条件是,给定三个KVP(A、B和C),要么需要A,要么需要B和C
因为它们实际上是独立可选的,所以我不能将它们标记为必需的,但是有效配置需要两个条件之一
我读过关于在Jon Rista上编写自定义验证器的文章,但这些只验证单个字段的值
我是否应该将这三个设置嵌套为它们自己的ConfigurationElement
,并为公开此部分的属性编写一个验证器(或使用CallbackValidator
)?或者有没有更好的方法来验证多个属性?如何使用
最后,我将这三个配置属性推送到一个定制的
ConfigurationElement
中,并在属性上使用CallbackValidator
:
public class AlphabetElement : ConfigurationElement
{
private static ConfigurationPropertyCollection _properties;
private static ConfigurationProperty _a;
[ConfigurationProperty("A")]
public Letter A
{
get { return (Letter)base[_a]; }
}
private static ConfigurationProperty _b;
[ConfigurationProperty("B")]
public Letter B
{
get { return (Letter)base[_b]; }
}
private static ConfigurationProperty _c;
[ConfigurationProperty("C")]
public Letter C
{
get { return (Letter)base[_c]; }
}
static AlphabetElement()
{
// Initialize the ConfigurationProperty settings here...
}
public static void Validate(object value)
{
AlphabetElement element = value as AlphabetElement;
if (element == null)
throw new ArgumentException(
"The method was called on an invalid object.", "value");
if (A == null && (B == null || C == null))
throw new ArgumentException(
"Big A, little a, bouncing beh... " +
"The system might have got you but it won't get me.");
}
}
public class BestBefore : ConfigurationSection
{
private static ConfigurationPropertyCollection _properties;
private static ConfigurationProperty _alphabetElement;
[ConfigurationProperty("alphabet", IsRequired = true)]
public AlphabetElement Alphabet
{
get { return (AlphabetElement)base[_alphabetElement]; }
}
static BestBefore()
{
_properties = new ConfigurationPropertyCollection();
_alphabetElement = new ConfigurationProperty(
"alphabet",
typeof(AlphabetElement),
null,
null,
new CallbackValidator(
typeof(AlphabetElement),
new ValidatorCallback(AlphabetElement.Validate)),
ConfigurationPropertyOptions.IsRequired);
_properties.Add(_alphabetElement);
}
}
然后在配置中,它看起来像:
<bestBefore ...>
<alphabet B="B" C="C"/>
</bestBefore>
我将把这个留给子孙后代
克拉斯同意
<bestBefore ...>
<alphabet B="B" C="C"/>
</bestBefore>