本篇体验扩展StringBuilder使之支持链式方法。
这里有一个根据键值集合生成select元素的方法。
private static string BuilderSelectBox(IDictionaryoptions, string id, bool includeUnknown){ var html = new StringBuilder(); html.AppendFormat(" "); return html.ToString();}
以上,
html.AppendFormat("<select id=\"{0}\" name=\"{0}\">", id);html.AppendLine();可以对这两个语句封装,扩展StringBuilder。 改成public static class StringBuilderExtensions{ public static StringBuilder AppendFormattedLine(this StringBuilder @this, string format, prams object[] args) => @this.AppendFormat(format, args).AppendLine();}private static string BuilderSelectBox(IDictionaryoptions, string id, bool includeUnknown){ var html = new StringBuilder() .AppendFormattedLine(" "); return html.ToString();}
以上,
if(includeUnknown) { html.AppendLine("\t<option>Unknown</option>"); }可以对如上语句进行封装,继续扩展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, Funcpredicate, string value) => predicate() ? @this.AppendLine(value) : @this; }private static string BuilderSelectBox(IDictionary options, string id, bool includeUnknown){ var html = new StringBuilder() .AppendFormattedLine(" "); return html.ToString();}
或
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, Funcpredicate, string value) => predicate() ? @this.AppendLine(value) : @this; public static StringBuilder AppendWhen(this StringBuilder @this, Func predicate, Func fn) => predicate() ? fn(@this) : @this; }private static string BuilderSelectBox(IDictionary options, string id, bool includeUnknown){ var html = new StringBuilder() .AppendFormattedLine(" "); return html.ToString();}
以上,
foreach(var opt in options) { html.AppendFormattedLine("\t<option value=\"{0}\">{1}</option>", opt.Key, opt.Value); } 对遍历语句进行封装,扩展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, Funcpredicate, string value) => predicate() ? @this.AppendLine(value) : @this; public static StringBuilder AppendWhen(this StringBuilder @this, Func predicate, Func fn) => predicate() ? fn(@this) : @this; public static StringBuilder AppendSequence (this StringBuilder @this, IEnumerable seq, Func fn) => seq.Aggregate(@this, fn); }private static string BuilderSelectBox(IDictionary options, string id, bool includeUnknown){ var html = new StringBuilder() .AppendFormattedLine(" ") .ToString();}