Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# .Net-DataAnnotations-验证2相关日期时间_C#_Validation_.net 3.5_Data Annotations - Fatal编程技术网

C# .Net-DataAnnotations-验证2相关日期时间

C# .Net-DataAnnotations-验证2相关日期时间,c#,validation,.net-3.5,data-annotations,C#,Validation,.net 3.5,Data Annotations,假设我上了以下课程: public class Post { public Date BeginDate { get; set; } [Validate2Date(BeginDate, EndDate, ErrorMessage = "End date have to occurs after Begin Date")] public Date EndDate { get; set; } } public class Validate2Dates : Validat

假设我上了以下课程:

public class Post 
{
    public Date BeginDate { get; set; }

    [Validate2Date(BeginDate, EndDate, ErrorMessage = "End date have to occurs after Begin Date")]
    public Date EndDate { get; set; }
}

public class Validate2Dates : ValidationAttribute
{
    public Validate2Dates(DateTime a, DateTime b)
    { ... }

    public override bool IsValid(object value)
    {
        // Compare date and return false if b < a
    }
}
我得到了以下错误:

非静态字段、方法或对象需要对象引用 属性“…Post.BeginDate.get”C:…\Post.cs


不能使用这样的属性。属性参数仅限于常量值


在我看来,更好的解决方案是在类上提供一个实现此检查的方法,并且可以通过您喜欢的业务逻辑验证接口调用该方法。

答案是肯定的,您可以做您尝试做的事情,而不是您当前做的方式。(顺便说一句,我刚刚注意到这个问题已经得到了很好的回答,所以我想我至少应该快速引用一下。)

基于上面的链接

  • 您需要编写一个自定义验证器(您已经完成了)
  • 您需要在类级别而不是属性级别装饰模型
  • 您不会将属性本身用作参数,而是将它们作为字符串引用,以便通过反射进行查找
  • [验证日期(开始日期、结束日期等)

    变成

    [Validate2Date(StartDate=“BeginDate”,EndDate=“EndDate”…

    然后,您将重写IsValid(),并反映执行比较所需的属性


    完全不同意。您不能像上面所写的那样专门使用验证属性,这是正确的。但是,他试图解决的问题是使用验证属性完美解决的。我相信,您是对的,将验证逻辑本身滚动到一个可重用组件中是有意义的,然后您可以利用该组件在一个验证属性中输入,并将其简单地插入到其余的DataAnnotation和模型绑定机制中。
    [Validate2Date(BeginDate, EndDate, ErrorMessage = "End date have to occurs before Begin Date")]
    
    .... 
            var properties = TypeDescriptor.GetProperties(value);
            object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
            object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
            return Object.Equals(originalValue, confirmValue);
    ....