本文轉載:http://www.cnblogs.com/jeffwongishandsome/archive/2009/11/18/1602825.html數據庫
下面這個是筆者在之前的一個項目中用到的。當時是爲了在導出excel報表的時侯,經過自定義特性,包含一些可配置的特性在裏面。具體的操做excel不是本文重點,本文不會多作說明。下面只寫個示例,簡單說明一下如何經過反射獲取自定義特性。示例只在類和屬性上使用了自定義特性。讀者能夠按照實際的項目需求,合理使用自定義特性。c#
一、實現實體自定義特性,繼承自Attribute類app
Code
///<summary> /// 自定義特性 屬性或者類可用 支持繼承 ///</summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited =true)] publicclass EnitityMappingAttribute : Attribute { privatestring tableName; ///<summary> /// 實體實際對應的表名 ///</summary> publicstring TableName { get { return tableName; } set { tableName = value; } }
privatestring columnName; ///<summary> /// 中文列名 ///</summary> publicstring ColumnName { get { return columnName; } set { columnName = value; } } }
註釋中我已經寫的很清楚,自定義特性中的屬性一個是實體實際對應的數據庫表名,一個是對應的中文列名稱。 二、在實體中使用自定義特性post
Code
///<summary> /// 會員 ,實際的表名叫MemberInfo,並非和實體名一致 ///</summary> [EnitityMapping(TableName="MemberInfo")] publicclass Member { privateint id; [EnitityMapping(ColumnName="關鍵字")] publicint Id { get { return id; } set { id = value; } }
privatestring userName; [EnitityMapping(ColumnName ="會員註冊名")] publicstring UserName { get { return userName; } set { userName = value; } }
privatestring realName; [EnitityMapping(ColumnName ="會員真實名")] publicstring RealName { get { return realName; } set { realName = value; } }
privatebool isActive; ///<summary> /// 是否活躍 沒有附加自定義屬性 ///</summary> publicbool IsActive { get { return isActive; } set { isActive = value; } } }
三、顯示自定義特性this
Code
class Program { ///<summary> /// 經過反射取自定義屬性 ///</summary> ///<typeparam name="T"></typeparam> privatestaticvoid 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); } } }
staticvoid Main(string[] args) { DisplaySelfAttribute<Member>(); //顯示結果 Console.ReadLine(); } }