選項1 - 使用運行時文本模板
作爲一個優雅的解決方案,您可以使用Run-time Text Templates。添加運行文本模板的一個新的項目到項目,並命名該文件ResearchRequestTemplate.tt
把這個內容是:
<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ parameter name="FellowDisplayName" type="System.String"#>
<#@ parameter name="ResearchProjectTitle" type="System.String"#>
<#@ parameter name="ResourceManagerDisplayName" type="System.String"#>
Hello <#= FellowDisplayName #>
You have requested access to the <#= ResearchProjectTitle #> Project.
Please submit all paperwork and badge ID to <#= ResourceManagerDisplayName #>
然後使用這種方式:
var template = new ResearchRequestTemplate();
template.Session = new Dictionary<string, object>();
template.Session["FellowDisplayName"]= value1;
template.Session["ResearchProjectTitle"]= value2;
template.Session["ResourceManagerDisplayName"] = value3;
template.Initialize();
var result = template.TransformText();
這是一種非常靈活的方式和你可以簡單地擴展它,因爲visual studio爲你的模板生成一個C#類,例如你可以爲它創建一個部分類,並在其中添加一些屬性並簡單地使用類型化屬性。
選擇2 - 命名的String.Format
可以使用指定的字符串格式的方法:
這裏是an implementation by James Newton:
public static class Extensions
{
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());
}
}
和使用:
"{CurrentTime} - {ProcessName}".FormatWith(
new { CurrentTime = DateTime.Now, ProcessName = p.ProcessName });
你也可以看看an implementation by Phil Haack。