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

Làm việc với Attribute trong C#

Attribute: Thẻ khai báo gắn metadata cho code (class, method, property...). Dùng ngoặc vuông [ ].

Cú pháp

[AttributeName(positionalParams, NamedParam = value)]
targetElement

Hai loại Attribute

  • Pre-defined: Obsolete, Serializable, Conditional, DllImport...
  • Custom: Tự định nghĩa kế thừa System.Attribute

Tạo Custom Attribute

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class BugFixAttribute : System.Attribute
{
    public int BugId { get; }
    public string Developer { get; set; }
    public DateTime Date { get; set; }
    
    public BugFixAttribute(int bugId) { BugId = bugId; }
}

// Sử dụng
[BugFix(123, Developer = "An", Date = "2024-01-15")]
public class MyClass { }

Đọc Attribute tại Runtime (Reflection)

var attrs = typeof(MyClass).GetCustomAttributes(true);
foreach (var attr in attrs)
    Console.WriteLine($"Bug #{attr.BugId} by {attr.Developer}");

AttributeTargets: All, Class, Struct, Method, Property, Field, Parameter, Assembly, Module, ...