您应该使用 System.ComponentModel.DataAnnotations
首先创建抽象类Bank
abstract class Bank
{
#region fields
private List<string> errorMessages = new List<string>();
#endregion
#region publioc methods
public virtual void Validate()
{
ValidateRulesAtributes();
}
#endregion
#region helper methods
private void ValidateRulesAtributes()
{
var validationContext = new ValidationContext(this, null, null); //ValidationContext -> Reference System.ComponentModel.DataAnnotations
var result = new List<ValidationResult>();
Validator.TryValidateObject(this, validationContext, result, true);
result.ForEach(p => { errorMessages.Add(p.ErrorMessage); });
if (errorMessages.Any())
throw new Exception(errorMessages.Aggregate((m1, m2) => String.Concat(m1, Environment.NewLine, m2)));
}
protected void Validate(List<string> messages)
{
if (errorMessages == null)
errorMessages = new List<string>();
if (messages != null)
messages.ForEach(p => { errorMessages.Add(p); });
ValidateRulesAtributes();
}
#endregion
#region properties
//Abstract to indicate Validation atributes
public abstract string AccountNumber { get; set; }
public abstract double Amount { get; set; }
public abstract int InvoicePeriod { get; set; }
#endregion
}
第二次使用数据注释创建红色和蓝色银行
class BlueBank : Bank
{
//All is ok, no validate
public override string AccountNumber { get; set; }
public override double Amount { get; set; }
public override int InvoicePeriod { get; set; }
}
class RedBank : Bank
{
[Required()]
public override string AccountNumber { get; set; }
public override double Amount { get; set; }
[Range(0,0)]
public override int InvoicePeriod { get; set; }
public override void Validate()
{
List<string> errors=new List<string>();
if (AccountNumber != "Test")
errors.Add("Worng Account");
base.Validate(errors);
}
}
使用属性来验证范围、要求等。覆盖 Validate() 以进行复杂的验证
这是一个简单的例子
class Program
{
static void Main(string[] args)
{
RedBank red = new RedBank();
red.AccountNumber = "Test";
red.Amount=0;
red.Validate(); //this No fail
red.InvoicePeriod = 3; //This Fail;
red.Validate();
red.AccountNumber = "PD";
red.Validate(); //this fal:
}
}