C#.Net下的Github开源库SmartFormat是一个字符串组合库,基本兼容并扩展加强了string.Format。SmartFormat可以使用命名占位符、列表、复数和其他智能扩展格式化数据。
SmartFormat是一个轻量级模板库,重点是语法。
它赋予数据驱动的模板具有适当的多元化、列表和条件语言逻辑。命名占位符提供了一种更直观、更不容易出错的方法来引入变量。
支持bool型条件判断的字符串格式化
string result= Smart.Format("Enabled? {0:Yes|No}", false);
以上代码将输出“Enabled?No”
string result= Smart.Format("Enabled? {0:Yes|No}", true);
那么以上代码将输出“Enabled?Yes”
也就是支持模板语句条件判断
支持日期格式条件判断的字符串格式化
string result = Smart.Format("My birthday {0:was on|will be on} {0:MMMM d}", new DateTime(2016, 10, 04));
以上代码将输出“My birthday was on 十月 4”
如果我将日期改为2022年的则会输出
result = Smart.Format("My birthday {0:was on|will be on} {0:MMMM d}", new DateTime(2022, 10, 04));
以上代码将输出“My birthday will be on 十月 4”
这个功能在某些场景下可以简化很多代码逻辑。
支持整形数量条件判断的字符串格式化
var emails = new List<string>() { "email1", "email2", "email3" };
string result = Smart.Format("You have {0} new {0:message|messages}", emails.Count);
emails是一个集合,有三个元素email1、email2、email3,则结果将会输出“You have 3 new messages”
如果emails集合里面只有一个元素则会输出“You have 1 new message”
注意:message这个词
支持名称占位符和索引参数的字符串格式化
var user = new[] { new { Name = "John", Gender = 0 }, new { Name = "Mary", Gender = 1 } };
string result = Smart.Format("{Name} commented on {Gender:his|her|their} photo", user[1]);
以上代码将输出“Mary commented on her photo”
注意:{Name}占位符已经被替换为数组索引为1里面的Mary,而Gender则被替换为her(因为Gender为1,则选择的是her,如果Gender=2,则会替换为their)
var user = new[] { new { Name = "John", Gender = 0 }, new { Name = "Mary", Gender = 1 } };
Smart.Default.Parser.UseAlternativeEscapeChar('\\'); // inmportant
string result = Smart.Format("{1:{Name}} commented on {1:{Gender:his|her|their}} photo", user);
这段代码输出和上个例子一样的内容“Mary commented on her photo”
支持集合输出的字符串格式化
var Users = new[] { new { Name = "Jim" }, new { Name = "Pam" }, new { Name = "Dwight" }, new { Name = "Michael" } };
string result = Smart.Format("{Users:{Name}|, | and } liked your comment", new object[] { new { Users = Users } });
以上代码将会输出“Jim, Pam, Dwight and Michael liked your comment” ,它通过模板语句直接将Users数组里面的Name格式化输出了
支持逻辑判断条件的字符串格式化
var emails = new List<string>() { "email1", "email2", "email3" };
string result = Smart.Format("You have {Messages.Count:choose(0|1):no new messages|a new message|{} new messages}", new object[] { new { Messages = emails } });
以上代码将输出“You have 3 new messages”
如果这个例子直接用C#自带的实现,代码如下
string result = $"You have {(emails.Count == 0 ? "no new messages" : emails.Count + " new messages")}";
输出结果是一样的,感觉比它的模板语句易读性会更好些,代码也更简洁。
名称占位符的字符串格式化
var addrList = new[] { new { Name = "Jim", Address = new { City = "New York", State = "NY" } } };
string result = Smart.Format("{Name} from {Address.City}, {Address.State}", addrList);
以上代码将输出“Jim from New York, NY”
更多示例可以参考SmartFormat的帮助文档
点评
总体来说是是通过自定义的一些语法模板来实现一些逻辑功能,个人感觉有些功能确实简化了一些代码,但整体可读性并不是特别的高,实用性并没有那么的强,可能某些场景下可以使用到。