首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

反射學習系列 2-特性 (一) 特性基礎與 TableAttribute 定義

     編輯:關於C語言

特性命名慣例

編譯器遇到特性(如 [Table])會自動在名稱後附加 Attribute 形成 TableAttribute 並搜尋該類別。若特性名稱已以 Attribute 結尾,則不再附加。所有特性繼承自 System.Attribute。

AttributeUsage 定義特性使用範圍

[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:同一目標不可重複套用同一特性(此處假設一個實體只映射一張表)。

完整 TableAttribute 範例

[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,避免衍生實體自動繼承資料表名稱,需顯式指定。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved