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

Lớp StringTemplate trong C#

StringTemplate thuộc thư viện NString (NuGet: NString), cung cấp formatting với named placeholder thay vì positional {0}.

Cài đặt

dotnet add package NString

Ví dụ sử dụng

using NString;

class Program
{
    static void Main()
    {
        var person = new { Name = "An", Age = 25, City = "Hà Nội" };
        
        // StringTemplate.Format - named placeholders
        string result = StringTemplate.Format(
            "{Name} is {Age} years old, lives in {City}", 
            person);
        
        Console.WriteLine(result);
        // Output: An is 25 years old, lives in Hà Nội
        
        // So với String.Format (positional)
        string oldWay = string.Format("{0} is {1} years old, lives in {2}", 
            person.Name, person.Age, person.City);
        
        // Format datetime
        var exam = new { ExamName = "Midterm", ExamDate = DateTime.Now };
        string formatted = StringTemplate.Format(
            "{ExamName} will held on {ExamDate:yyyy-MM-dd}", 
            exam);
        Console.WriteLine(formatted);
    }
}

So sánh

Đặc điểmString.FormatStringTemplate.Format
PlaceholderSố thứ tự {0}, {1}Tên property {Name}, {Age}
Đọc hiểuKhó với nhiều tham sốDễ đọc, tự tài liệu hóa
Thứ tựPhụ thuộc vị tríKhông phụ thuộc thứ tự
Type safetyRuntimeRuntime (reflection)
PerformanceNhanh hơnChậm hơn (reflection)

C# 6+ String Interpolation (built-in, khuyên dùng)

var person = new { Name = "An", Age = 25 };
string modern = $"{person.Name} is {person.Age} years old";
// Nhanh, type-safe, readable - không cần thư viện ngoài

Lưu ý: StringTemplate dùng reflection → chậm hơn. Ưu tiên $"" interpolation (C# 6+) cho hầu hết trường hợp.