Attribute(特性)是 C# 中為程式碼元素附加中繼資料的強大機制。本文示範如何利用自訂 Attribute 實現物件關係映射(ORM)的核心功能,將類別對應資料表、屬性對應欄位。
編譯器偵測到 Attribute 時,會在名稱後附加 Attribute 後綴(若原名已含則不加),於命名空間搜尋對應類別。所有 Attribute 必須繼承 System.Attribute。
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class TableAttribute : Attribute {
private string tableName;
public string TableName {
get { return tableName; }
set { tableName = value; }
}
public TableAttribute() { this.tableName = null; }
public TableAttribute(string tableName) { this.tableName = tableName; }
}
AttributeUsage 限定僅能套用於類別、不可重複、不繼承。
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ColumnAttribute : Attribute {
private string columnName;
private DbType dbType;
public string ColumnName { get { return columnName; } set { columnName = value; } }
public DbType DbType { get { return dbType; } set { dbType = value; } }
public ColumnAttribute() { this.columnName = null; this.dbType = DbType.String; }
public ColumnAttribute(string columnName) { this.columnName = columnName; }
public ColumnAttribute(string columnName, DbType dbType) : this(columnName) { this.dbType = dbType; }
}
[Table("UserInfo")]
public class UserInfo {
private int userId;
[Column("UserId", DbType.Int32)]
public int UserId { get { return userId; } set { userId = value; } }
private string userName;
[Column("UserName", DbType.String)]
public string UserName { get { return userName; } set { userName = value; } }
}
UserInfo userInfo = new UserInfo();
Type type = userInfo.GetType();
TableAttribute ta = (TableAttribute)type.GetCustomAttributes(false)[0];
Console.WriteLine("資料表名:" + ta.TableName);
PropertyInfo[] infos = type.GetProperties();
foreach (PropertyInfo info in infos) {
object[] attributes = info.GetCustomAttributes(false);
foreach (object att in attributes) {
if (att is ColumnAttribute) {
ColumnAttribute ca = att as ColumnAttribute;
string cn = ca.ColumnName == null ? info.Name : ca.ColumnName;
Console.WriteLine("欄位名:" + cn);
Console.WriteLine("欄位型別:" + ca.DbType);
}
}
}

此模式為 Entity Framework 等成熟 ORM 框架的核心基礎,理解其運作有助於深入掌握框架內部機制。