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; }
 }
相关推荐
乱世军军1 天前
把 Python 3.13 降级到 3.11
开发语言·python
本喵是FW1 天前
C语言手记2
c语言·开发语言
fy121631 天前
GO 快速升级Go版本
开发语言·redis·golang
共享家95271 天前
Java入门(String类)
java·开发语言
0xDevNull1 天前
Spring Boot 循环依赖解决方案完全指南
java·开发语言·spring
bbq粉刷匠1 天前
Java--多线程--单例模式
java·开发语言·单例模式
dfafadfadfafa1 天前
嵌入式C++安全编码
开发语言·c++·算法
计算机安禾1 天前
【C语言程序设计】第34篇:文件的概念与文件指针
c语言·开发语言·数据结构·c++·算法·visual studio code·visual studio
弦有三种苦难1 天前
CCF-202412-T3缓存模拟90分
java·开发语言·spring
会编程的土豆1 天前
【数据结构与算法】 二叉树做题
开发语言·数据结构·c++·算法