編譯器遇到特性(如 [Table])會自動在名稱後附加 Attribute 形成 TableAttribute 並搜尋該類別。若特性名稱已以 Attribute 結尾,則不再附加。所有特性繼承自 System.Attribute。
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class TableAttribute : Attribute
{
private string _tableName;
public TableAttribute() { }
public TableAttribute(string tableName) { _tableName = tableName; }
public string TableName
{
get { return _tableName; }
set { _tableName = value; }
}
}
AttributeTargets.Class:只能套用於類別/介面/結構等型別宣告。Inherited = true:套用於基類別的特性會自動套用至衍生類別。AllowMultiple = false:同一目標不可重複套用同一特性(此處假設一個實體只映射一張表)。[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class TableAttribute : Attribute
{
private string _tableName;
public TableAttribute() { }
public TableAttribute(string tableName) { _tableName = tableName; }
public string TableName
{
get { return _tableName; }
set { _tableName = value; }
}
}
此處設定 Inherited = false,避免衍生實體自動繼承資料表名稱,需顯式指定。