您的位置:首页 > 编程语言

实体验证---测试代码

2014-12-15 14:34 190 查看
文章出处:/article/5461039.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;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: