你的位置:首页 > 软件开发 > ASP.net > C#中扩展StringBuilder支持链式方法

C#中扩展StringBuilder支持链式方法

发布时间:2016-03-13 13:00:05
本篇体验扩展StringBuilder使之支持链式方法。这里有一个根据键值集合生成select元素的方法。 private static string BuilderSelectBox(IDictionary<int, string> options, strin ...

 

本篇体验扩展StringBuilder使之支持链式方法。这里有一个根据键值集合生成select元素的方法。

 

private static get='_blank'>string BuilderSelectBox(IDictionary<int, string> options, string id, bool includeUnknown){  var html = new StringBuilder();  html.AppendFormat("<select id=\"{0}\" name=\"{0}\">", id);  html.AppendLine();    if(includeUnknown)  {    html.AppendLine("\t<option>Unknown</option>");  }    foreach(var opt in options)  {    html.AppendFormat("\t<option value=\"{0}\">{1}</option>", opt.Key, opt.Value);    html.AppendLine();  }    html.AppendLine("</select>");    return html.ToString();}
html.AppendFormat("<select id=\"{0}\" name=\"{0}\">", id);可以对这两个语句封装,扩展StringBuilder。    if(includeUnknown)可以对如上语句进行封装,继续扩展StringBuilder.

 

public static class StringBuilderExtensions{  public static StringBuilder AppendFormattedLine(this StringBuilder @this, string format, prams object[] args) => @this.AppendFormat(format, args).AppendLine();    public static StringBuilder AppendLineWhen(this StringBuilder @this, Func<bool> predicate, string value) =>  predicate()     ? @this.AppendLine(value)    : @this;  }private static string BuilderSelectBox(IDictionary<int, string> options, string id, bool includeUnknown){  var html = new StringBuilder()    .AppendFormattedLine("<select id=\"{0}\" name=\"{0}\">", id)    .AppendLineWhen(() => includeUnknown, "\t<option>Unknown</option>");    foreach(var opt in options)  {    html.AppendFormattedLine("\t<option value=\"{0}\">{1}</option>", opt.Key, opt.Value);  }    html.AppendLine("</select>");    return html.ToString();}
    foreach(var opt in options)

原标题:C#中扩展StringBuilder支持链式方法

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录