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

Chuỗi định dạng (Formatted String Literals) trong C#

C# có 2 cách chính format string: String.Format (composite formatting) và String Interpolation $"" (C# 6+).

1. String.Format (Classic)

using System;

class Program
{
    static void Main()
    {
        decimal temp = 15.2m;
        string res = String.Format("Temperature = {0}°C.", temp);
        Console.WriteLine(res);
        
        // Multiple args
        string name = "An"; int age = 25;
        Console.WriteLine(String.Format("{0} is {1} years old", name, age));
        
        // Format specifiers
        Console.WriteLine(String.Format("{0:C}", 1234.56));     // Currency: $1,234.56
        Console.WriteLine(String.Format("{0:P}", 0.1234));      // Percent: 12.34%
        Console.WriteLine(String.Format("{0:N}", 1234567));     // Number: 1,234,567.00
        Console.WriteLine(String.Format("{0:F2}", 3.14159));    // Fixed 2 decimals: 3.14
    }
}

2. String Interpolation (C# 6+) - Khuyên dùng

decimal temp = 15.2m;
string name = "An"; int age = 25;

Console.WriteLine($"Temperature = {temp}°C.");
Console.WriteLine($"{name} is {age} years old");

// Format specifiers trong interpolation
double price = 1234.56;
Console.WriteLine($"Price: {price:C}");      // Currency
Console.WriteLine($"Price: {price:C2}");     // 2 decimals
Console.WriteLine($"Pi: {Math.PI:F4}");      // 3.1416
Console.WriteLine($"Percent: {0.123:P1}");   // 12.3%

// Alignment
Console.WriteLine($"|{"Name",-10}|{"Age",5}|");
Console.WriteLine($"|{"An",-10}|{25,5}|");
Console.WriteLine($"|{"Binh",-10}|{30,5}|");

3. FormattableString (Advanced)

using System;

FormattableString fs = $"Name: {name}, Age: {age}";
Console.WriteLine(fs.Format);  // "Name: {0}, Age: {1}"
Console.WriteLine(fs.GetArguments().Length); // 2

// Dùng cho logging, SQL parameterization
void Log(FormattableString msg) 
{
    // msg.Format, msg.GetArguments() - an toàn SQL injection
    Console.WriteLine(msg.ToString());
}

Kết quả đầu ra

Temperature = 15.2°C.
An is 25 years old
$1,234.56
12.34%
1,234,567.00
3.14
|Name      |Age  |
|An        |   25|
|Binh      |   30|

Best Practice: Dùng $"" interpolation cho hầu hết trường hợp. String.Format cho format pattern từ config/file. FormattableString cho logging/SQL safety.