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

Visual C# 定義與使用自訂屬性 (3):套用屬性與讀取驗證

     編輯:關於C語言

套用自訂屬性

在目標型別/方法前以方括號標記:

using MyAttributeClasses;

namespace SomeClassesToTest
{
    [DefectTrack("1377", "12/15/02", "David Tansey")]
    [DefectTrack("1363", "12/12/02", "Toni Feltman", Origin = "Coding: Unhandled Exception")]
    public class SomeCustomPricingClass
    {
        public double GetAdjustedPrice(double price, double pct) { return price + price * pct; }

        [DefectTrack("1351", "12/10/02", "David Tansey", Origin = "Specification: Missing Requirement", FixComment = "Added PriceIsValid()")]
        public bool PriceIsValid(double price) { return price > 0 && price < 1000; }
    }

    [DefectTrack("NEW", "12/12/02", "Mike Feltman")]
    public class AnotherCustomClass
    {
        [DefectTrack("1399", "12/17/02", "David Tansey", Origin = "Analysis: Missing Requirement")]
        public void SetMessage(string msg) { /*...*/ }
    }
}

屬性 vs 原始碼註解

  • 屬性編譯進中繼資料,無原始碼時仍可讀取。
  • 註解編譯後遺失,僅存在原始碼。
  • 屬性可在設計時建構實例,提供結構化資料。

使用 ILDASM 驗證屬性存在

ILDASM 顯示屬性中繼資料

圖中可見 .custom 指令包含屬性型別與建構函式參數,證明屬性已嵌入組件。

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