屬性 vs 類別屬性
| 比較項目 | 自訂屬性 | 類別屬性 |
| 適用目標 | 組件、類別、方法、參數、欄位等 13 種目標 | 僅限類別/結構成員 |
| 儲存位置 | 中繼資料,編譯時期固化 | 執行期實例記憶體,可變更 |
| 實例關聯 | 套用於型別定義,所有實例共享相同值 | 屬於特定實例 |
建立 DefectTrackAttribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class DefectTrackAttribute : Attribute
{
private string _defectID, _developerID, _defectOrigin, _fixComment;
private DateTime _modificationDate;
public DefectTrackAttribute() { }
public DefectTrackAttribute(string defectID, string modDate, string devID)
{
_defectID = defectID;
_modificationDate = DateTime.Parse(modDate);
_developerID = devID;
}
public string DefectID { get { return _defectID; } }
public string ModificationDate { get { return _modificationDate.ToShortDateString(); } }
public string DeveloperID { get { return _developerID; } }
public string Origin { get { return _defectOrigin; } set { _defectOrigin = value; } }
public string FixComment { get { return _fixComment; } set { _fixComment = value; } }
}
AttributeUsage 關鍵設定
AttributeTargets.Class | AttributeTargets.Method:限定套用目標。
AllowMultiple = true:允許同一目標套用多次(記錄多次修改)。
Inherited = false (預設):衍生類別不繼承,避免混淆來源。
屬性類別結構
- 繼承
System.Attribute。
- 私有欄位儲存資料。
- 建構函式參數 = 位置參數(必填),唯讀屬性公開。
- 公開屬性含 set = 命名參數(選填)。