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

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
大猫的无限游戏
大猫的无限游戏
博客园 - 聂微东
Jina AI
Jina AI
The Cloudflare Blog
V
Visual Studio Blog
博客园_首页
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 【当耐特】
爱范儿
爱范儿
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
博客园 - 司徒正美
阮一峰的网络日志
阮一峰的网络日志
Last Week in AI
Last Week in AI
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 叶小钗
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
博客园 - Franky

博客园 - ∈鱼杆

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