∈鱼杆 ---我的鱼塘

执着,坚定,友爱,勇敢(www.pumaboyd.com)Live Message

导航

HowTo:String.Format新方法

Posted on 2009-01-14 14:13  ∈鱼杆  阅读(384)  评论(0编辑  收藏  举报

挺有意思的一个扩展方法,分享给大家(原作者链接在最后)
一般情况我们都习惯了这样写
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