码迷,mamicode.com
首页 > 其他好文 > 详细

实体验证---测试代码

时间:2014-12-15 15:21:20      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   ar   sp   for   on   log   bs   

文章出处:http://www.cnblogs.com/tristanguo/archive/2009/05/15/1457197.html

 

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            user u = new user() { userAge = 9, userName = "rree" };
            if (u.Checked().ToList().Count>0)
            {
                u.Checked().ToList().ForEach(d => Console.WriteLine(d));
            }

            Console.Read();
        }
    }

    public class user : EntityBase
    {
        public string userName { set; get; }
        public int userAge { set; get; }

        public IEnumerable<String> Checked()
        {
            return new Validator<user>(this)
            .Validata(u => u.userAge > 10, "age must larger than 10")
            .Validata(u => u.userName.Length > 3, "user name must larger than 3")
            .ErrorList;
        
        }
    }

    public abstract class EntityBase
    { }

    public class Validator<T> where T : EntityBase
    {
        private T entity;
        List<string> errorList = new List<string>();

        public Validator(T tEntity)
        {
            entity = tEntity;
        }

        public List<string> ErrorList
        {
            get { return errorList; }
        }

        public Validator<T> Validata(Predicate<T> predicate, string errMsg)
        {
            if (!predicate(entity))
            {
                this.errorList.Add(errMsg);
            }
            return this;
        }
    }

}

实体验证---测试代码

标签:blog   http   io   ar   sp   for   on   log   bs   

原文地址:http://www.cnblogs.com/movemoon/p/4164821.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!