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

Ký tự @ trước chuỗi trong C#: Verbatim String Literal

Verbatim String Literal là gì?

Ký tự @ trước chuỗi (ví dụ: @"...") đánh dấu verbatim string literal - chuỗi nguyên văn.

Đặc điểm chính

  • Bỏ qua escape sequences: \n, \t, \\, \"... được coi là ký tự thường.
  • Cho phép xuống dòng: Chuỗi có thể trải dài nhiều dòng.
  • Dấu " trong chuỗi: Viết "" (hai dấu nháy kép) thay vì \".

So sánh: Regular vs Verbatim

Regular StringVerbatim String (@)Kết quả
"Line1\nLine2"@"Line1\nLine2"Regular: 2 dòng. Verbatim: 1 dòng có chữ \n
"C:\\Path\\File.txt"@"C:\Path\File.txt"Cùng kết quả: C:\Path\File.txt
"He said \"Hi\""@"He said ""Hi"""Cùng kết quả: He said "Hi"
Không thể multi-lineCó thể multi-lineVerbatim linh hoạt hơn

Ví dụ thực tế


using System;
using System.IO;

class Program 
{
    static void Main() 
    {
        // 1. File path - không cần escape \
        string path1 = @"D:\Projects\MyApp\bin\Debug\config.json";
        string path2 = "D:\\Projects\\MyApp\\bin\\Debug\\config.json"; // Tương đương
        
        // 2. Multi-line string (SQL, JSON, HTML, XML)
        string sql = @"
            SELECT u.Name, u.Email
            FROM Users u
            WHERE u.IsActive = 1
            ORDER BY u.CreatedDate DESC";
        
        string json = @"
        {
            ""name"": ""John"",
            ""age"": 30,
            ""city"": ""Hanoi""
        }";
        
        // 3. Dấu " trong chuỗi
        string quote = @"He said ""Hello World!"" to me";
        // Kết quả: He said "Hello World!" to me
        
        // 4. Regular string với escape
        string regular = "Line1\nLine2\tTabbed";
        string verbatim = @"Line1\nLine2\tTabbed";
        
        Console.WriteLine("Regular:");
        Console.WriteLine(regular);
        Console.WriteLine("Verbatim:");
        Console.WriteLine(verbatim);
        
        // 5. File.ReadAllText - cả hai cách đều OK
        var content1 = File.ReadAllText(@"D:\Data\file.txt");
        var content2 = File.ReadAllText("D:\\Data\\file.txt");
    }
}

Kết quả Regular vs Verbatim

Regular:
Line1
Line2   Tabbed
Verbatim:
Line1\nLine2\tTabbed

Raw String Literals (C# 11+) - Tính năng mới

Thay thế verbatim string cho multi-line phức tạp:


// C# 11+ - Raw string literals (dấu """)
string sql = """
    SELECT u.Name, u.Email
    FROM Users u
    WHERE u.IsActive = 1
    ORDER BY u.CreatedDate DESC
    """;

// Có thể dùng " trong chuỗi tự nhiên
string json = """
    {
        "name": "John",
        "age": 30,
        "city": "Hanoi"
    }
    """;

// Kiểm soát indentation - đóng dấu """ quyết định base indentation
string indented = """
    {
        "name": "John",
        "age": 30
    }
    """; // JSON không có indent thừa

Interpolated Verbatim String


var name = "John";
var age = 30;

// C# 6+ - Interpolated verbatim
var s1 = $@"Name: {name}
Age: {age}";

// C# 11+ - Raw interpolated
var s2 = $"""
    Name: {name}
    Age: {age}
    """;

Khi nào dùng cái nào?

LoạiUse Case
Regular "..."Chuỗi đơn giản, có escape sequences (\n, \t), single line
Verbatim @"..."File path, regex pattern, multi-line đơn giản, C# < 11
Raw """..."""Multi-line phức tạp (JSON, SQL, HTML, XML), C# 11+
Interpolated $"..."Chuỗi có biến, expression
Interpolated Verbatim $@"..."Multi-line + interpolation
Raw Interpolated $"""..."""Multi-line phức tạp + interpolation (C# 11+)

Lưu ý hiệu năng

  • Verbatim string compile-time constant → cùng performance với regular string.
  • Raw string literals cũng được resolve tại compile time.
  • Không có overhead runtime so với regular string.