using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.EnterpriseLibrary.Validation; using ValidationResult = System.ComponentModel.DataAnnotations.ValidationResult; namespace Blackice.Suite.Domains.Validations { /// <summary> /// 企业库验证操作 /// </summary> public class Validation : IValidation { /// <summary> /// 验证 /// </summary> /// <param name="target">验证目标</param> public ValidationResultCollection Validate(object target) { var validator = ValidationFactory.CreateValidator(target.GetType()); var results = validator.Validate(target); return GetResult(results); } /// <summary> /// 获取验证结果 /// </summary> private ValidationResultCollection GetResult(IEnumerable<Microsoft.Practices.EnterpriseLibrary.Validation.ValidationResult> results) { var result = new ValidationResultCollection(); foreach (var each in results) result.Add(new ValidationResult(each.Message)); return result; } } /// <summary> /// 验证操作 /// </summary> public interface IValidation { /// <summary> /// 验证 /// </summary> /// <param name="target">验证目标</param> ValidationResultCollection Validate(object target); } /// <summary> /// 验证结果集合 /// </summary> public class ValidationResultCollection : IEnumerable<ValidationResult> { /// <summary> /// 初始化验证结果集合 /// </summary> public ValidationResultCollection() { _results = new List<ValidationResult>(); } /// <summary> /// 验证结果 /// </summary> private readonly List<ValidationResult> _results; /// <summary> /// 是否有效 /// </summary> public bool IsValid { get { return _results.Count == 0; } } /// <summary> /// 验证结果个数 /// </summary> public int Count { get { return _results.Count; } } /// <summary> /// 添加验证结果 /// </summary> /// <param name="result">验证结果</param> public void Add(ValidationResult result) { if (result == null) return; _results.Add(result); } /// <summary> /// 添加验证结果集合 /// </summary> /// <param name="results">验证结果集合</param> public void AddResults(IEnumerable<ValidationResult> results) { if (results == null) return; foreach (var result in results) Add(result); } /// <summary> /// 获取迭代器 /// </summary> IEnumerator<ValidationResult> IEnumerable<ValidationResult>.GetEnumerator() { return _results.GetEnumerator(); } /// <summary> /// 获取迭代器 /// </summary> IEnumerator IEnumerable.GetEnumerator() { return _results.GetEnumerator(); } public IEnumerator GetEnumerator() { return _results.GetEnumerator(); } } }
时间: 2024-12-16 02:34:35