C# 字符串占位

Githubhttps://github.com/jonatasolmartins/smart-strings

SmartStrings 是一个轻量级且直观的 C​​# 字符串模板库。它添加了扩展方法,.Fill()允许您使用对象、字典或参数数组替换字符串中的占位符,并提供可选的回退方案。

复制代码
using SmartStrings;

static void Main(string[] args)
{
    var template = "Welcome, {user}!";
    var result = template.Fill("Alice");
    Console.WriteLine(result);
    // Output: "Welcome, Alice!"

    template = "Hello {name}, your {plan} plan is active.";
    result = template.Fill("Jonatas", "Gold");
    Console.WriteLine(result);
    // Output: "Hello Jonatas, your Gold plan is active."s


    template = "Welcome {name}, your ID is {id}.";
    result = template.Fill(new { name = "Lucas", id = "12345" });
    Console.WriteLine(result);
    // Output: "Welcome Lucas, your ID is 12345."

    template = "Welcome {name}, your ID is {id}.";
    result = template.Fill(new User { Name = "ccc", Id = 1 });
    Console.WriteLine(result);
    // Output: "Welcome ccc, your ID is 1."

    template = "{\"Id\":\"{id}\",\"Name\":\"{name}\",\"Age\":-{age}}";
    result = template.Fill(new User { Name = "ccc", Id = 1, Age = 10 });
    Console.WriteLine(result);
    // Output: "{"Id":"1","Name":"ccc","Age":-10}"

    template = "https://api.company.com/v{version}/users/{userId}/orders?date={date:yyyy-MM-dd}&status={status:active}";
    result = template.Fill(new
    {
        version = 2,
        userId = "abc123",
        date = DateTime.Now,
        status = "pending"
    });
    Console.WriteLine(result);
    // Output: "https://api.company.com/v2/users/abc123/orders?date=2025-12-19&status=pending"

    Console.ReadKey();
}

 public class User
 {
     public string Name { get; set; }
     public int Id { get; set; }

     public int Age { get; set; }
 }
相关推荐
拾贰_C1 小时前
[Python | pytorch | torchvision ] models like ResNet... 命名变量说明
开发语言·pytorch·python
傅里叶的耶1 小时前
C++ Primer Plus(第6版):第三章 处理数据
开发语言·c++
CC.GG2 小时前
【C++】AVL树
java·开发语言·c++
CoderCodingNo2 小时前
【GESP】C++四级真题 luogu-B4416 [GESP202509 四级] 最长连续段
开发语言·c++·算法
a程序小傲2 小时前
京东Java面试被问:Fork/Join框架的使用场景
java·开发语言·后端·postgresql·面试·职场和发展
⑩-2 小时前
Java四种线程创建方式
java·开发语言
月光在发光2 小时前
22_GDB调试记录(未完成)
java·开发语言
222you2 小时前
SpringAOP的介绍和入门
java·开发语言·spring
程序员zgh2 小时前
代码重构 —— 读后感
运维·c语言·开发语言·c++·重构