新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
C#中如何使用反射以及特性簡化-創(chuàng)新互聯(lián)
本篇文章給大家分享的是有關(guān)C#中如何使用反射以及特性簡化,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
假設(shè)現(xiàn)在有一個(gè)學(xué)生類(Student)
{ { name = Age { ; Address { ;
如果需要判斷某些字段(屬性)是否為空,是否大于0,便有以下代碼:
public static string ValidateStudent(Student student) { StringBuilder validateMessage = new StringBuilder(); if (string.IsNullOrEmpty(student.Name)) { validateMessage.Append("名字不能為空"); } if (string.IsNullOrEmpty(student.Sex)) { validateMessage.Append("性別不能為空"); } if (student.Age <= 0) { validateMessage.Append("年齡必填大于0"); } //...... 幾百行 // 寫到這里發(fā)現(xiàn)不對啊,如果必填項(xiàng)有20多個(gè),難道我要一直這樣寫嗎! return validateMessage.ToString(); }
這樣的代碼,重用性不高,而且效率低。
我們可以用特性,反射,然后遍歷屬性并檢查特性。
首先自定義一個(gè)【必填】特性類,繼承自Attribute
////// 【必填】特性,繼承自Attribute /// public sealed class RequireAttribute : Attribute { private bool isRequire; public bool IsRequire { get { return isRequire; } } ////// 構(gòu)造函數(shù) /// /// public RequireAttribute(bool isRequire) { this.isRequire = isRequire; } }
然后用這個(gè)自定義的特性標(biāo)記學(xué)生類的成員屬性:
////// 學(xué)生類 /// public class Student { ////// 名字 /// private string name; [Require(true)] public string Name { get { return name; } set { name = value; } } ////// 年齡 /// [Require(true)] public int Age { get; set; } ////// 地址 /// [Require(false)] public string Address { get; set; } ////// 性別 /// [Require(true)] public string Sex; }
通過特性檢查類的屬性:
////// 檢查方法,支持泛型 /// ////// /// public static string CheckRequire (T instance) { var validateMsg = new StringBuilder(); //獲取T類的屬性 Type t = typeof (T); var propertyInfos = t.GetProperties(); //遍歷屬性 foreach (var propertyInfo in propertyInfos) { //檢查屬性是否標(biāo)記了特性 RequireAttribute attribute = (RequireAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof (RequireAttribute)); //沒標(biāo)記,直接跳過 if (attribute == null) { continue; } //獲取屬性的數(shù)據(jù)類型 var type = propertyInfo.PropertyType.ToString().ToLower(); //獲取該屬性的值 var value = propertyInfo.GetValue(instance); if (type.Contains("system.string")) { if (string.IsNullOrEmpty((string) value) && attribute.IsRequire) validateMsg.Append(propertyInfo.Name).Append("不能為空").Append(","); } else if (type.Contains("system.int")) { if ((int) value == 0 && attribute.IsRequire) validateMsg.Append(propertyInfo.Name).Append("必須大于0").Append(","); } } return validateMsg.ToString(); }
執(zhí)行驗(yàn)證:
static void Main(string[] args) { var obj = new Student() { Name = "" }; Console.WriteLine(CheckRequire(obj)); Console.Read(); }
結(jié)果輸出:
有人會(huì)發(fā)現(xiàn),Sex也標(biāo)記了[Require(true)],為什么沒有驗(yàn)證信息,這是因?yàn)椋琒ex沒有實(shí)現(xiàn)屬性{ get; set; },GetProperties是獲取不到的
以上就是C#中如何使用反射以及特性簡化,小編相信有部分知識點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)頁題目:C#中如何使用反射以及特性簡化-創(chuàng)新互聯(lián)
路徑分享:http://www.ef60e0e.cn/article/dgcgeh.html