控制自訂特性可套用的目標元素、是否允許重複、是否可繼承等。
將列舉視為位元旗標而非獨立值:
[Flags]
enum Animal
{
Dog = 0x0001,
Cat = 0x0002,
Duck = 0x0004,
Chicken = 0x0008
}
Animal animals = Animal.Dog | Animal.Cat;
Console.WriteLine(animals); // 輸出 "Dog, Cat" 而非 "3"
呼叫非受控程式碼(Win32 API):
[DllImport("User32.dll")]
public static extern int MessageBox(int hWnd, string text, string caption, int type);
MessageBox(0, "Hello .NET", "Title", 0);
標記型別可序列化,支援二進制、XML、JSON 等序列化格式。
條件編譯,常用於除錯:
[Conditional("DEBUG")]
void DebugLog(string msg) { Console.WriteLine(msg); }
// 只有定義 DEBUG 符號時才會編譯呼叫
Description、DefaultValue、Category:設計工具支援ReadOnly、Browsable:屬性格控制[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
public class TestAttribute : Attribute
{
public TestAttribute(string message)
{
Console.WriteLine(message);
}
public void RunTest() => Console.WriteLine("TestAttribute here.");
}
[Test("Error Here.")]
public void CannotRun() { }
var tp = typeof(Tester);
var method = tp.GetMethod("CannotRun");
var attr = (TestAttribute)Attribute.GetCustomAttribute(method, typeof(TestAttribute));
attr?.RunTest();
#if/#endif 的靈活條件編譯特性 是 .NET 中繼資料系統的核心擴展機制。掌握內建特性並能建立自訂特性,是開發高階框架、程式碼分析工具、序列化引擎的關鍵能力。