ref: https://www.cnblogs.com/woadmin/p/9406970.html
特性類的使用過程:
第一步:定義一個特性類,定義一些成員來包含驗證時需要的數據;
第二步:創建特性類實例;
創建一個特性類的實例,里面包含着驗證某一個屬性或者字段需要的數據。
將該實例關聯到某個屬性上面。
第三步:使用特性類實例
可以通過調用某個類型的GetProperties()方法,獲取屬性,
然后調用類型屬性成員的GetCustomAttributes()方法,獲取該屬性關聯的特性類實例,
然后使用查找到的特性類實例驗證新建對象。
第二步:創建一個特性類的實例,並關聯一個屬性
public class Order
{
[StringLength("訂單號", 6, MinLength = 3, ErrorMessage = "{0}的長度必須在{1}和{2}之間!")]//實例化一個特性類,關聯到一個字段上面
public string OrderID { get; set; }
}
第三步:使用特性類實例,進行驗證
class Program
{
#region 使用特性類的過程
//驗證過程
//1.通過映射,找到成員屬性關聯的特性類實例,
//2.使用特性類實例對新對象的數據進行驗證
//用特性類驗證訂單號長度
public static bool isIDLengthValid(int IDLength, MemberInfo member)
{
foreach (object attribute in member.GetCustomAttributes(true)) //2.通過映射,找到成員屬性上關聯的特性類實例,
{
if (attribute is StringLengthAttribute)//3.如果找到了限定長度的特性類對象,就用這個特性類對象驗證該成員
{
StringLengthAttribute attr = (StringLengthAttribute)attribute;
if (IDLength < attr.MinLength || IDLength > attr.MaxLength)
{
string displayName = attr.DisplayName;
int maxLength = attr.MaxLength;
int minLength = attr.MinLength;
string error = attr.ErrorMessage;
Console.WriteLine(error, displayName,maxLength, minLength);//驗證失敗,提示錯誤
return false;
}
else return true;
}
}
return false;
}
//驗證訂單對象是否規范
public static bool isOrderValid(Order order)
{
if (order == null) return false;
foreach (PropertyInfo p in typeof(Order).GetProperties())
{
if (isIDLengthValid(order.OrderID.Length, p))//1記錄下新對象需要驗證的數據,
return true;
}
return false;
}
#endregion
public static void Main()
{
Order order=new Order();
do
{
Console.WriteLine("請輸入訂單號:");
order.OrderID= Console.ReadLine();
}
while (!isOrderValid(order));
Console.WriteLine("訂單號輸入正確,按任意鍵退出!");
Console.ReadKey();
}
}
總結:特性類的實例里沒有驗證邏輯,只有驗證用到的規范數據(比如字符串長度)、提示信息等。驗證邏輯需要自己寫。



