溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#中如何使用反射以及特性簡化

發(fā)布時間:2020-07-14 10:39:31 來源:億速云 閱讀:154 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關(guān)C#中如何使用反射以及特性簡化,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

假設(shè)現(xiàn)在有一個學(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多個,難道我要一直這樣寫嗎!
            return validateMessage.ToString();
        }

這樣的代碼,重用性不高,而且效率低。

我們可以用特性,反射,然后遍歷屬性并檢查特性。

首先自定義一個【必填】特性類,繼承自Attribute

    /// <summary>
    /// 【必填】特性,繼承自Attribute    /// </summary>
    public sealed class RequireAttribute : Attribute
    {        private bool isRequire;        public bool IsRequire
        {            get { return isRequire; }
        }        /// <summary>
        /// 構(gòu)造函數(shù)        /// </summary>
        /// <param name="isRequire"></param>
        public RequireAttribute(bool isRequire)
        {            this.isRequire = isRequire;
        }
    }

然后用這個自定義的特性標(biāo)記學(xué)生類的成員屬性:

/// <summary>
    /// 學(xué)生類    /// </summary>
    public class Student
    {   
        /// <summary>
        /// 名字        /// </summary>
        private string name;
        [Require(true)]        public string Name
        {            get { return name; }            set { name = value; }
        }        /// <summary>
        /// 年齡        /// </summary>
        [Require(true)]        public int Age { get; set; }        /// <summary>
        /// 地址        /// </summary>
        [Require(false)]        public string Address { get; set; }        /// <summary>
        /// 性別        /// </summary>
        [Require(true)] 
        public string Sex;
    }

通過特性檢查類的屬性:

  /// <summary>
        /// 檢查方法,支持泛型        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="instance"></param>
        /// <returns></returns>
        public static string CheckRequire<T>(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é)果輸出:

C#中如何使用反射以及特性簡化

有人會發(fā)現(xiàn),Sex也標(biāo)記了[Require(true)],為什么沒有驗(yàn)證信息,這是因?yàn)?,Sex沒有實(shí)現(xiàn)屬性{ get; set; },GetProperties是獲取不到的

以上就是C#中如何使用反射以及特性簡化,小編相信有部分知識點(diǎn)可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI