Attributes dùng thêm metadata: compiler instructions, comments, description, methods, classes vào chương trình.
Attribute định nghĩa sẵn này đánh dấu conditional method thực thi phụ thuộc preprocessing identifier.
Nó gây conditional compilation của method calls, phụ thuộc giá trị như Debug hoặc Trace. Ví dụ: hiển thị giá trị biến khi debug code.
Cú pháp conditional attributes:
[Conditional(conditionalSymbol)]
Cách làm việc với Conditional attributes:
Ví dụ
#define DEBUG
using System;
using System.Diagnostics;
public class Myclass {
[Conditional("DEBUG")]
public static void Message(string msg) {
Console.WriteLine(msg);
}
}
class Test {
static void function1() {
Myclass.Message("In Function 1");
function2();
}
static void function2() {
Myclass.Message("In Function 2");
}
public static void Main() {
Myclass.Message("In Main function");
function1();
Console.ReadKey();
}
}
Kết quả
In Main function
In Function 1
In Function 2