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; }
 }
相关推荐
aini_lovee6 小时前
MATLAB基于小波技术的图像融合实现
开发语言·人工智能·matlab
R1nG8637 小时前
多线程安全设计 CANN Runtime关键数据结构的锁优化
开发语言·cann
初次见面我叫泰隆7 小时前
Qt——5、Qt系统相关
开发语言·qt·客户端开发
亓才孓7 小时前
[Class的应用]获取类的信息
java·开发语言
开开心心就好7 小时前
AI人声伴奏分离工具,离线提取伴奏K歌用
java·linux·开发语言·网络·人工智能·电脑·blender
Never_Satisfied7 小时前
在JavaScript / HTML中,关于querySelectorAll方法
开发语言·javascript·html
3GPP仿真实验室7 小时前
【Matlab源码】6G候选波形:OFDM-IM 增强仿真平台 DM、CI
开发语言·matlab·ci/cd
devmoon7 小时前
在 Polkadot 上部署独立区块链Paseo 测试网实战部署指南
开发语言·安全·区块链·polkadot·erc-20·测试网·独立链
lili-felicity7 小时前
CANN流水线并行推理与资源调度优化
开发语言·人工智能
沐知全栈开发7 小时前
CSS3 边框:全面解析与实战技巧
开发语言