实体验证demo

 平时主要工作是做cs,上午花了两个小时写了个通用的 实体验证,感觉多不错。 下面是另外一个人写的,可以对比一下http://www.cnblogs.com/tristanguo/archive/2009/05/15/1457197.html

思路:一个实体的基类,主要用于后面的泛型,  具体的实体类User 继承, 具体的一个实体验证逻辑是 通过委托的方法 存在于实体中,在验证之前由调用者决定

需要做的验证。最后返回一个错误的集合。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            User u = new User() { Name = "Dylan", Age = 17 };

    //Build check list

            u.CheckList.Add(u.CheckList_Age);
            u.CheckList.Add(u.CheckList_Name);
            IEnumerable<String> errorList = u.Check();

            foreach (string a in errorList)
            {
                Console.WriteLine(a);
            }
            Console.Read();
        }
    }

  //base class

    public class EntityBase
    {
        public List<CustomePredicate<User>> CheckList = new List<CustomePredicate<User>>();
        public virtual IEnumerable<String> Check()
        { return null; }
    }

 

  //entity class

    public class User : EntityBase
    {

    //check delegate
        public CustomePredicate<User> CheckList_Name = new CustomePredicate<User>("Name  lenght xiao 20", u => u.Name.Length < 20);
        public CustomePredicate<User> CheckList_Age = new CustomePredicate<User>("Age xiao 20 ", user => user.Age < 20);

 

        private Validator<User> validate = new Validator<User>();

   

        public String Name
        { get; set; }

        public Int32 Age
        { get; set; }

 

        public User()
            : base()
        { }

        public override IEnumerable<String> Check()
        {
            for (int i = 0; i < CheckList.Count; i++)
            {
                validate.Validate(CheckList[i].ErrorMessage, CheckList[i].Predicate, this);
            }
            return validate.ErrorList;
        }
    }

 

  //custome delegate

    public class CustomePredicate<T> where T : EntityBase
    {
        private Predicate<T> m_Predicate = null;
        public Predicate<T> Predicate
        { get { return m_Predicate; } }

 

        private String m_erroeMessage = String.Empty;
        public String ErrorMessage
        { get { return m_erroeMessage; } }

 

        public CustomePredicate(String errorMessage, Predicate<T> p)
        {
            m_erroeMessage = errorMessage;
            m_Predicate = p;
        }
    }

 

   //core class ,, validate class

    public class Validator<T> where T : EntityBase
    {
        private List<String> m_errorlist = new List<String>();
        public IEnumerable<String> ErrorList
        {
            get { return m_errorlist; }
        }

        public void Validate(String errorMessage, Predicate<T> predicate, T entity)
        {
            if (predicate(entity))
                m_errorlist.Add(errorMessage);
        }
    }
}

 

posted @ 2009-12-25 10:33  msp  阅读(265)  评论(0编辑  收藏  举报