下面這個是筆者在以前的一個項目中用到的。當時是為了在導出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();
}
}