C# 使用反射的自定义验证属性?

C# 使用反射的自定义验证属性?,c#,validation,attributes,annotations,C#,Validation,Attributes,Annotations,我想使用System.ComponentModel.DataAnnotations程序集来验证我正在处理的控制台应用程序的参数(映射到属性)。我将使用“buddy类”元数据模式;这在过去对我很有效 我需要验证的一件事是,只提供了两种类型的参数中的一种。换句话说,可以指定参数foo,也可以指定参数bar,但不能同时指定两者,也不能同时指定两者 为此,我开始编写一个定制的验证属性,这似乎相当简单,但当我意识到我需要访问验证上下文的属性之外,并遍历到我正在验证的对象中的同级属性(如CompareAtt

我想使用
System.ComponentModel.DataAnnotations
程序集来验证我正在处理的控制台应用程序的参数(映射到属性)。我将使用“buddy类”元数据模式;这在过去对我很有效

我需要验证的一件事是,只提供了两种类型的参数中的一种。换句话说,可以指定参数
foo
,也可以指定参数
bar
,但不能同时指定两者,也不能同时指定两者

为此,我开始编写一个定制的验证属性,这似乎相当简单,但当我意识到我需要访问验证上下文的属性之外,并遍历到我正在验证的对象中的同级属性(如
CompareAttribute
)时,我有点不知所措。这似乎是一个典型的反省案例,但我对如何进行还有些挠头。这就是我到目前为止所做的:

/// <summary>
/// This property, or the other specified, are required, but both cannot be set.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class XORAttribute : ValidationAttribute
{
    /// <summary>
    /// If validation should fail, return this error message.
    /// </summary>
    public string ErrorMessage { get; set; }
    /// <summary>
    /// The name of the other required property that is mutually exclusive of this one.
    /// </summary>
    public string OtherValueName { get; set; }

    public XORAttribute(string otherValueName)
    {
        this.OtherValueName = otherValueName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //Something needs to go here.
    }
}
//
///此属性或其他指定属性是必需的,但不能同时设置。
/// 
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
公共类XORAttribute:ValidationAttribute
{
/// 
///如果验证失败,则返回此错误消息。
/// 
公共字符串错误消息{get;set;}
/// 
///与此属性互斥的其他必需属性的名称。
/// 
公共字符串OtherValueName{get;set;}
公共XORAttribute(字符串otherValueName)
{
this.OtherValueName=OtherValueName;
}
受保护的重写ValidationResult有效(对象值,ValidationContext ValidationContext)
{
//这里需要一些东西。
}
}

在此提供一些帮助将不胜感激。

使用属性检查其他属性并不那么容易。答案是,嗯,不太漂亮

真的吗?没有接受者?我本以为这是一个简单的问题,对于在验证中有经验的ppl来说。这不是我想要的答案,但似乎是正确的答案。