一个用户实体应该有它自己的实体验证,即一个实体应该有它的属性,方法,扩展属性及验证机制组成

一个存储验证信息的公用类:

   /// <summary>
    /// 验证信息实体类
    /// </summary>
    public class RuleViolation
    {
        /// <summary>
        /// 属性名,only support contruction method set it
        /// </summary>
        public string PropertyName { get; private set; }
        /// <summary>
        /// 错误信息
        /// </summary>
        public string ErrorMessage { get; private set; }
        /// <summary>
        /// 为错误信息赋值
        /// </summary>
        /// <param name="errorMessage"></param>
        public RuleViolation(string errorMessage)
        {
            this.ErrorMessage = errorMessage;
        }
        /// <summary>
        /// 为指定属性赋错误信息
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="errorMessage"></param>
        public RuleViolation(string propertyName, string errorMessage)
        {
            this.PropertyName = propertyName;
            this.ErrorMessage = errorMessage;
        }
    }

一个要实现的验证功能的接口

 /// <summary>
    /// 数据实体验证统一接口
    /// </summary>
    public interface IEntity
    {
        /// <summary>
        /// 验证是否成功
        /// </summary>
        bool IsValid { get; }
        /// <summary>
        /// 如果GetRuleViolation返回的迭代数大于0,则IsValid赋值为假
        /// </summary>
        /// <returns></returns>
        IEnumerable<RuleViolation> GetRuleViolation();
    }

当这个接口被实现后,可以使用IsValid方法来判断你的实体是否满足条件!!!听起来有点抽象,现在我把它具体一下吧!

首先来一个实体对象

public partial class User:IEntity
{
  public String UserID { get; set; }

  public String UserName { get; set; }
}

   public partial class UserBase : IEntity
    {
       public bool IsValid
        {
            get { return (GetRuleViolations().Count() == 0); }
        }
        public IEnumerable<RuleViolation> GetRuleViolations()
        {
            if (String.IsNullOrEmpty(this.UserID))
                yield return new RuleViolation("不能为空", "UserID");
            if (!XValidator.IsRealLengthValid(this.UserID, 2, 12))
                yield return new RuleViolation("至少要有2个字符,同时不能多于12个字符", "UserID");
        }

   }

OK了,这样我们在使用User类时,如果要判断是赋值的是否合法,直接使用User.IsValid就可以了,哈哈!

posted @ 2011-05-18 14:31  张占岭  阅读(535)  评论(0编辑  收藏  举报