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

Cách xây dựng Custom Attribute (thuộc tính tùy chỉnh) trong C#

Attribute dùng để thêm metadata (chỉ thị compiler, mô tả, comment, method, class...) vào chương trình. .NET cho phép tạo custom attribute lưu thông tin khai báo và truy xuất tại runtime.

Custom attribute mới kế thừa từ System.Attribute.

Ví dụ: Attribute DeBugInfo lưu thông tin debug

using System;

// Chỉ định target và cho phép multiple
[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; // Named parameter (optional)
    
    // Positional parameters (bắt buộc)
    public DeBugInfo(int bg, string dev, string d)
    {
        this.bugNo = bg;
        this.developer = dev;
        this.lastReview = d;
    }
    
    // Properties read-only cho positional params
    public int BugNo { get { return bugNo; } }
    public string Developer { get { return developer; } }
    public string LastReview { get { return lastReview; } }
    
    // Named parameter có set/get
    public string Message 
    { 
        get { return message; } 
        set { message = value; } 
    }
}

Sử dụng attribute:

[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
[DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
class Rectangle { ... }

Truy xuất tại runtime (Reflection):

var attrs = typeof(Rectangle).GetCustomAttributes(typeof(DeBugInfo), false);
foreach (DeBugInfo dbi in attrs)
    Console.WriteLine($"Bug {dbi.BugNo}: {dbi.Developer} - {dbi.Message}");

AttributeTargets: All, Assembly, Class, Struct, Enum, Constructor, Method, Property, Field, Event, Interface, Parameter, Delegate, ReturnValue, GenericParameter.