แอตทริบิวต์ใช้สำหรับเพิ่มข้อมูลเมตา เช่น คำสั่งคอมไพเลอร์และข้อมูลอื่นๆ เช่น ความคิดเห็น คำอธิบาย เมธอด และคลาสในโปรแกรม
.Net Framework อนุญาตให้สร้างแอตทริบิวต์ที่กำหนดเองที่สามารถใช้เพื่อเก็บข้อมูลการประกาศและสามารถดึงข้อมูลได้ในขณะใช้งาน
แอตทริบิวต์ที่กำหนดเองใหม่ได้มาจากคลาส System.Attribute
//a custom attribute BugFix to be assigned to a class and its members [AttributeUsage( AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] public class DeBugInfo : System.Attribute
ให้เราสร้างแอตทริบิวต์ที่กำหนดเองชื่อ DeBugInfo ซึ่งเก็บข้อมูลที่ได้รับจากการดีบักโปรแกรมใดๆ
คลาส DeBugInfo มีคุณสมบัติส่วนตัวสามประการสำหรับการจัดเก็บข้อมูลสามรายการแรกและคุณสมบัติสาธารณะสำหรับการจัดเก็บข้อความ ดังนั้นหมายเลขบั๊ก ชื่อผู้พัฒนา และวันที่ตรวจสอบจึงเป็นพารามิเตอร์ตำแหน่งของคลาส DeBugInfo และข้อความเป็นพารามิเตอร์ทางเลือกหรือระบุชื่อ
ตัวอย่าง
มาดูกันว่า −
//a custom attribute BugFix to be assigned to a class and its members
[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;
}
}
}