惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
Vercel News
Vercel News
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
量子位
Engineering at Meta
Engineering at Meta
B
Blog RSS Feed
博客园 - 【当耐特】
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
D
DataBreaches.Net
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
人人都是产品经理
人人都是产品经理
IT之家
IT之家
T
The Blog of Author Tim Ferriss
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Jina AI
Jina AI
博客园 - 三生石上(FineUI控件)

博客园 - ∈鱼杆

TraceView .NET WAP网站开发系列 ASP.NET RSS开发札记(完结) MonoRail MVC实践应用(完结) HowTo:C#性能测试扩展函数 Python性能测试工具 Excel分类汇总宏(VBA) Python性能测试工具 HowTo:C#性能测试扩展函数 MonoRailMVC应用-母板页的Title 面向方面的编程在Cache、Log、Trace方面的运用 MonoRail MVC应用(2)-构建多层结构的应用程序 MonoRail MVC应用(1)-VM/HTML页面 MonoRail MVC实践应用 W3WP进程CPU查看 innerHTML和P标签 [转] 有关敏捷的若干思考 .NET WAP开发及兼容问题 ASP.NET分页控件(AspNetPager分页控件)
HowTo:String.Format新方法
∈鱼杆 · 2009-01-14 · via 博客园 - ∈鱼杆

挺有意思的一个扩展方法,分享给大家(原作者链接在最后)
一般情况我们都习惯了这样写
String.Format(”{0} last logged in at {1}”,”pumaboyd”,”2009-1-1″)
这东西本身是没什么问题,但当 {0}, {1}, {2} 多了,你根本就不知道具体对应关系是什么。
如果能这样就比较好了
String.Format(”{UserName} last logged in at {LoginDate}”,”pumaboyd”,”2009-1-1″)
通过名词来标识,而不是{0}.这个需求是可以满足的,通过扩展方法就可以实现:
调用方法:

"{UserName} last logged in at {LoginDate}".FormatWith(new { UserName = "pumaboyd", LoginDate = "2009-1-1" });

扩展方法:

public static string FormatWith(this string format, object source)   {   return FormatWith(format, null, source);   }       public static string FormatWith(this string format, IFormatProvider provider, object source)   {   if (format == null)   throw new ArgumentNullException("format");       Regex r = new Regex(@"(?<start>\{)+(?<property>[\w\.\[\]]+)(?<format>:[^}]+)?(?<end>\})+",   RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);       List<object> values = new List<object>();   string rewrittenFormat = r.Replace(format, delegate(Match m)   {   Group startGroup = m.Groups["start"];   Group propertyGroup = m.Groups["property"];   Group formatGroup = m.Groups["format"];   Group endGroup = m.Groups["end"];       values.Add((propertyGroup.Value == "0")   ? source   : DataBinder.Eval(source, propertyGroup.Value));       return new string('{', startGroup.Captures.Count) + (values.Count - 1) + formatGroup.Value   + new string('}', endGroup.Captures.Count);   });       return string.Format(provider, rewrittenFormat, values.ToArray());   }

(*^__^*)感觉不错吧!特别注意一下其中的DataBinder.Eval的用法噢!
引用:
http://james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-named-variables.aspx