文章出處
文章列表
using EntryRegistration.Filters; using EntryRegistration.Models.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace EntryRegistration.Models { public class Check { /// <summary> /// 檢查方法,支持泛型 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance"></param> /// <returns></returns> public static CheckResult CheckRequire<T>(T instance) { //初始化驗證結果 CheckResult result = new CheckResult() { isSuccess = true, msg = "驗證OK" }; //獲取T類的屬性 Type t = typeof(T); var propertyInfos = t.GetProperties(); //遍歷屬性 foreach (var propertyInfo in propertyInfos) { //檢查屬性是否標記了特性 RequireAttribute attribute = (RequireAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(RequireAttribute)); //沒標記,直接跳過 if (attribute == null) { continue; } //獲取該屬性的值 var value = propertyInfo.GetValue(instance); //獲取屬性的數據類型 if (typeof(string) == propertyInfo.PropertyType) { if (string.IsNullOrEmpty((string)value) && attribute.IsRequire) { result.isSuccess = false; result.msg = propertyInfo.Name + "不能為空"; return result; } } else if (typeof(int?) == propertyInfo.PropertyType) { if (value == null && attribute.IsRequire) { result.isSuccess = false; result.msg = propertyInfo.Name + "不能為空"; return result; } } else if (typeof(Guid) == propertyInfo.PropertyType) { if (Guid.Parse(value.ToString()) == Guid.Empty && attribute.IsRequire) { result.isSuccess = false; result.msg = propertyInfo.Name + "不能為空"; return result; } } } return result; } } }
//RequireAttribute.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace EntryRegistration.Filters { public class RequireAttribute : Attribute { public bool IsRequire { get; } /// <summary> /// 構造函數 /// </summary> /// <param name="isRequire"></param> public RequireAttribute(bool IsRequire) { this.IsRequire = IsRequire; } } }
文章列表
全站熱搜