C# 字符串占位

Github :https://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; }
 }
相关推荐
雪域迷影22 分钟前
Python Django 7 小时课程
开发语言·python·django
Escalating_xu1 小时前
【C 语言】编译和链接:从源文件、目标文件到可执行程序完整解析
c语言·开发语言
Liuqy-051 小时前
线程的互斥与同步机制——互斥锁、条件变量、无名信号量
linux·开发语言·线程·进程·条件变量·同步·互斥
geats人山人海1 小时前
java 7异常
android·java·开发语言
Pniubi2 小时前
分片的意义?
java·开发语言
阿皮 API2 小时前
Shopee虾皮商品详情API接口调用实战:Python获取东南亚商品数据与JSON解析
开发语言·python·json
niucloud-admin2 小时前
NIUCLOUD LITE AI开发文档--系统部署
开发语言·ai
多弗朗皮卡丘2 小时前
C++异常
开发语言·c++·异常
米糕闯编程3 小时前
鱼香ros2(十七)C++小海龟巡逻
开发语言·c++·机器人·ros2·服务·小海龟
郝学胜-神的一滴3 小时前
NumPy深度解析|Python数值计算的基石,告别低效for循环
开发语言·人工智能·python·程序人生·numpy·量化投资