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; }
 }
相关推荐
码云数智-大飞几秒前
零拷贝 IPC:用内存映射文件打造 .NET 高性能进程间通信队列
java·开发语言·网络
懈尘4 分钟前
深入理解Java的HashMap扩容机制
java·开发语言·数据结构
Beginner x_u6 分钟前
JavaScript 核心知识索引(面试向)
开发语言·javascript·面试·八股
yqd6667 分钟前
RabbitMQ用法和面试题
java·开发语言·面试
白日梦想家68113 分钟前
JavaScript性能优化实战系列(三篇完整版)
开发语言·javascript·性能优化
请注意这个女生叫小美13 分钟前
C语言 实例20 25
c语言·开发语言·算法
fundroid14 分钟前
Kotlin 泛型进阶:in、out 与 reified 实战
android·开发语言·kotlin
枫叶丹418 分钟前
【Qt开发】Qt系统(十一)-> Qt 音频
c语言·开发语言·c++·qt·音视频
tlwlmy21 分钟前
python excel图片批量导出
开发语言·python·excel
散峰而望24 分钟前
【基础算法】穷举的艺术:在可能性森林中寻找答案
开发语言·数据结构·c++·算法·随机森林·github·动态规划