Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách tạo Custom Attribute (Thuộc tính tùy chỉnh) trong C#

Custom attribute lưu thông tin khai báo và có thể truy xuất tại runtime.

Khai báo custom attribute

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

Ví dụ xây dựng DeBugInfo lưu thông tin debug: bug number, developer, date review (positional params), message (named param).

Ví dụ hoàn chỉnh

[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; } }
}