c#通過反射獲取類上的自定義特性


下面這個是筆者在以前的一個項目中用到的。當時是為了在導出excel報表的時侯,通過自定義特性,包含一些可配置的特性在里面。具體的操作excel不是本文重點,本文不會多做說明。下面只寫個示例,簡單說明一下如何通過反射獲取自定義特性。示例只在類和屬性上使用了自定義特性。讀者可以按照實際的項目需求,合理使用自定義特性。

1、實現實體自定義特性,繼承自Attribute類


   /// <summary>
    /// 自定義特性 屬性或者類可用  支持繼承
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = true)]
    public class EnitityMappingAttribute : Attribute
    {
        private string tableName;
        /// <summary>
        /// 實體實際對應的表名
        /// </summary>
        public string TableName
        {
            get { return tableName; }
            set { tableName = value; }
        }

        private string columnName;
        /// <summary>
        /// 中文列名
        /// </summary>
        public string ColumnName
        {
            get { return columnName; }
            set { columnName = value; }
        }
    }

注釋中我已經寫的很清楚,自定義特性中的屬性一個是實體實際對應的數據庫表名,一個是對應的中文列名稱。
2、在實體中使用自定義特性


 /// <summary>
    /// 會員 ,實際的表名叫MemberInfo,並不是和實體名一致
    /// </summary>
    [EnitityMapping(TableName="MemberInfo")] 
    public class Member
    {
        private int id;
        [EnitityMapping(ColumnName="關鍵字")]
        public int Id
        {
            get { return id; }
            set { id = value; }
        }

        private string userName;
        [EnitityMapping(ColumnName = "會員注冊名")]
        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }

        private string realName;
        [EnitityMapping(ColumnName = "會員真實名")]
        public string RealName
        {
            get { return realName; }
            set { realName = value; }
        }

        private bool isActive;
        /// <summary>
        /// 是否活躍  沒有附加自定義屬性
        /// </summary>
        public bool IsActive
        {
            get { return isActive; }
            set { isActive = value; }
        }
    }

3、顯示自定義特性


   class Program
    {
        /// <summary>
        /// 通過反射取自定義屬性
        /// </summary>
        /// <typeparam name="T"></typeparam>
        private static void DisplaySelfAttribute<T>() where T:class ,new()
        {
            string tableName = string.Empty;
            List<string> listColumnName = new List<string>();
            Type objType = typeof(T);
            //取屬性上的自定義特性
            foreach (PropertyInfo propInfo in objType.GetProperties())
            {
                object[] objAttrs = propInfo.GetCustomAttributes(typeof(EnitityMappingAttribute), true);
                if (objAttrs.Length>0)
                {
                    EnitityMappingAttribute attr = objAttrs[0] as EnitityMappingAttribute;
                    if (attr != null)
                    {
                        listColumnName.Add(attr.ColumnName); //列名
                    }
                }
            }

            //取類上的自定義特性
            object[] objs = objType.GetCustomAttributes(typeof(EnitityMappingAttribute), true);
            foreach (object obj in objs)
            {
                EnitityMappingAttribute attr = obj as EnitityMappingAttribute;
                if (attr != null)
                {

                    tableName = attr.TableName;//表名只有獲取一次
                    break;
                }
            }
            if (string.IsNullOrEmpty(tableName))
            {
                tableName = objType.Name;
            }
            Console.WriteLine(string.Format("The tablename of the entity is:{0} ", tableName));
            if (listColumnName.Count > 0)
            {
                Console.WriteLine("The columns of the table are as follows:");
                foreach (string item in listColumnName)
                {
                    Console.WriteLine(item);
                }
            }
        }

        static void Main(string[] args)
        {
            DisplaySelfAttribute<Member>(); //顯示結果
            Console.ReadLine();
        }
    }
ps:在獲取自定義特性的地方,其實就是利用了GetCustomAttributes方法,這個沒什么好說的。在實際開發的時候,通過反射的特性可以省卻我們很多繁瑣的事情,真像那句話說的,“反射反射,程序員的快樂”。不過,反射的性能問題還是需要格外注意的,比如,今天上午看到老趙的“ Attribute操作的性能優化方式”才發現原來還有那么多內涵。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM