Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีสร้าง Custom Attributes ใน C#

Custom attributes ใช้เก็บข้อมูลประกาศ และดึงข้อมูลได้ในรันไทม์

การประกาศ Custom Attribute

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] 
public class DeBugInfo : System.Attribute

ตัวอย่าง: สร้าง custom attribute ชื่อ DeBugInfo เก็บข้อมูลจากการ debug โปรแกรม

คลาส DeBugInfo มี property private 3 ตัว สำหรับข้อมูล 3 อย่างแรก และ property public 1 ตัวสำหรับข้อความ หมายเลขบั๊ก ชื่อนักพัฒนา และวันที่ตรวจสอบเป็น positional parameters ข้อความเป็น named parameter

แอตทริบิวต์ทุกตัวต้องมี constructor อย่างน้อย 1 ตัว

ตัวอย่าง

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] 
public class DeBugInfo : System.Attribute { 
    private int bugNo; 
    private string developer; 
    private string lastReview; 
    public string message; 
    public DeBugInfo(int bg, string dev, string d) { 
        this.bugNo = bg; this.developer = dev; this.lastReview = d; 
    } 
    public int BugNo { get { return bugNo; } } 
    public string Developer { get { return developer; } } 
    public string LastReview { get { return lastReview; } } 
    public string Message { 
        get { return message; } 
        set { message = value; } 
    } 
}