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

#if DEBUG trong C# là gì? Cách sử dụng và ví dụ chi tiết

Debug vs Release Mode

Đặc điểmDebug ModeRelease Mode
Mục đíchDebug từng dòng codeBuild bản phân phối
Tối ưu hóa codeKhông tối ưuTối ưu đầy đủ
Thông tin debugĐầy đủ (symbols, PDB)Không có
BreakpointChính xácCó thể không chính xác do tối ưu
Hiệu năngChậm hơnNhanh hơn

Cách chuyển đổi cấu hình Build

  • Menu Build → Configuration Manager → Chọn Debug hoặc Release.
  • Hoặc toolbar: chọn Debug/Release từ dropdown Solution Configurations.

Cơ chế #if DEBUG

Code nằm trong block #if DEBUG ... #endif chỉ được biên dịch và thực thi khi build ở Debug mode. Ở Release mode, block này bị loại bỏ hoàn toàn tại compile time.

Ví dụ cơ bản

class Program 
{
    static void Main() 
    {
        #if DEBUG
        Console.WriteLine("Bạn đang chạy ở DEBUG mode");
        Console.WriteLine($"Thời gian: {DateTime.Now}");
        // Log chi tiết, kiểm tra biến, ghi file debug...
        #endif
        
        Console.WriteLine("Chương trình chạy bình thường");
        Console.ReadKey();
    }
}

Ví dụ nâng cao: Logging có điều kiện

public class Logger 
{
    public static void LogDebug(string message) 
    {
        #if DEBUG
        Console.ForegroundColor = ConsoleColor.Gray;
        Console.WriteLine($"[DEBUG {DateTime.Now:HH:mm:ss.fff}] {message}");
        Console.ResetColor();
        #endif
    }

    public static void LogInfo(string message) 
    {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine($"[INFO {DateTime.Now:HH:mm:ss}] {message}");
        Console.ResetColor();
    }

    public static void LogError(string message) 
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"[ERROR {DateTime.Now:HH:mm:ss}] {message}");
        Console.ResetColor();
    }
}

// Sử dụng
class Program 
{
    static void Main() 
    {
        Logger.LogInfo("Khởi động ứng dụng");
        
        #if DEBUG
        Logger.LogDebug("Kết nối database: Server=localhost;DB=Test");
        Logger.LogDebug("Config: Timeout=30s, Retry=3");
        #endif
        
        try 
        {
            // Logic nghiệp vụ
        }
        catch (Exception ex) 
        {
            Logger.LogError(ex.Message);
        }
    }
}

Các directive liên quan

  • #if DEBUG / #endif
  • #else - khối code cho Release mode
  • #elif - điều kiện else-if
  • #define DEBUG / #undef DEBUG - định nghĩa/ hủy symbol (thường do project settings quản lý)
  • [Conditional("DEBUG")] - attribute cho method (method chỉ được gọi ở Debug)

Ví dụ với Conditional Attribute

using System.Diagnostics;

public class DebugHelper 
{
    [Conditional("DEBUG")]
    public static void PrintDebugInfo(string info) 
    {
        Console.WriteLine($"[DEBUG] {info}");
    }
}

// Gọi: DebugHelper.PrintDebugInfo("Test");
// Ở Release: lời gọi này bị loại bỏ hoàn toàn khỏi IL

Lưu ý quan trọng

  • DEBUG symbol được định nghĩa tự động bởi Visual Studio/MSBuild cho Debug configuration.
  • Không hardcode #define DEBUG trong code - để build system quản lý.
  • Code trong #if DEBUG không tồn tại trong binary Release → an toàn cho thông tin nhạy cảm.
  • Tránh lạm dụng: logic nghiệp vụ quan trọng không nên đặt trong #if DEBUG.