Attributes ใช้เพิ่ม metadata เช่น compiler instructions, comments, descriptions, methods, classes ให้กับโปรแกรม
.NET Framework อนุญาตให้สร้าง custom attributes ที่เก็บข้อมูล declarative และดึงได้ในขณะรันไทม์
Custom attribute ใหม่ต้องสืบทอดจาก System.Attribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor |
AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property,
AllowMultiple = true)]
public class DeBugInfo : System.Attribute
สร้าง attribute DeBugInfo เก็บข้อมูลจากการ debug:
- bug number, developer name, review date = positional parameters
- message = named/optional parameter
ตัวอย่างการสร้าง DeBugInfo class
[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; }
}
}