我有一种情况,我想与字段进行比较(例如,确保开始时间在结束时间之前)。我正在使用这些System.ComponentModel.DataAnnotations
属性进行验证。
我的第一个想法是这样的:
public enum CompareToOperation
{
EqualTo,
LessThan,
GreaterThan
}
public class CompareToAttribute : ValidationAttribute
{
CompareToOperation _Operation;
IComparable _Comparision;
public CompareToAttribute(CompareToOperation operation, Func<IComparable> comparison)
{
_Operation = operation;
_Comparision = comparison();
}
public override bool IsValid(object value)
{
if (!(value is IComparable))
return false;
switch (_Operation)
{
case CompareToOperation.EqualTo: return _Comparision.Equals(value);
case CompareToOperation.GreaterThan: return _Comparision.CompareTo(value) == 1;
case CompareToOperation.LessThan: return _Comparision.CompareTo(value) == -1;
}
return false;
}
}
public class SimpleClass
{
public DateTime Start {get;set;}
[CompareTo(CompareToOperation.GreaterThan, () => this.Start)] // error here
public DateTime End {get;set;}
}
但是,这不起作用,标记属性的位置存在编译器错误:
Expression cannot contain anonymous methods or lambda expressions
有人对此有解决方案吗?或者与另一个字段的值相比,验证一个字段的不同方法?