2012-03-08 15 views
1

我的工作任务,需要一个很好的协议字符串操作,如:可以使用什么来获取超越String.Format的名称字符串模板?

string result = 
    String.Format("template text {0}, {1}, ... {150}", arg1, arg2, ... ,arg150); 

在考虑到大量的参数,这并不感到优雅,我担心的说法错误订购。

ASP.NET样式模板(即template text <%= arg1 %>, <%= arg2 %>,将是不错,但我不希望有做一个网络请求,Web服务器只是为了获得一个更好的模板引擎。

是否有更好的方式来做到这一点?

+0

你的参数是否在一个数组上,并且你只是想将它们连接在一起,用“,”开头用“模板文本”分隔? – dcarneiro 2012-03-08 15:04:47

+0

StringBuilder或List ? – shenhengbin 2012-03-08 15:05:45

+3

这里是一个重复的:http://stackoverflow.com/questions/733378/whats-a-good-way-of-doing-string-templating-in-net。更多的建议可以在这里找到:http://stackoverflow.com/questions/620265/can-i-set-up-html-email-templates-with-asp-net – Xaisoft 2012-03-08 15:07:30

回答

5

你可以尝试RazorEngine的基础上,剃刀

string template = 
    @"<html> 
     <head> 
     <title>Hello @Model.Name</title> 
     </head> 
     <body> 
     Email: @Html.TextBoxFor(m => m.Email) 
     </body> 
    </html>"; 

    var model = new PageModel { Name = "World", Email = "[email protected]" }; 
    string result = Razor.Parse(template, model); 
+0

我试过这个,它工作得很好。 – Xaisoft 2012-03-08 15:06:25

0

IF可以使用文本模板,你可以把你的字符串中StringBuilder,然后用适当的值替换出现的所有pattern。

0

我会说,如果你看看你所提供的字符串:

"template text {0}, {1}, ... {150}" 

和另一

template text <%= arg1 %>, <%= arg2 %> 

除了象征(特别是对于每一个技术),他们看起来similiar。所以我会说,你的解决方案已经很好了,imo。

或者您可以在字符串中使用“给定名称”,例如我们在SQL字符串中使用@parameter。因此,在参数本身中,您将对该参数有一些概念。

3

现代C#6和新型应用

随着C#的出现和String Interpolation在这个问题上最初的答案已经过时。字符串插值本质上是合法的,使string.Format。它允许你将C#和变量放在一个字符串中。触发字符串插值的语法是在字符串引号之前加上$,然后插入大括号内的任何内容。以下是一个将变量myName插入字符串的示例。

string myName= "Scott"; 
string text = $"Hello {myName}!"; 

这是所有内置于C#6和更新的应用程序,无需单独下载或库/包所需。

旧/过时的答案

你可以使用第三方模板框架。目前我最喜欢的是Mustache,因为它几乎在每种语言中都很简单和实现。 .NET库为它是Nustache

的语法模板是这样的:

This is my template I will insert a {{mustache}} right there. 

下面是.NET的代码示例。

using Nustache.Core; 

string template = "This is my template I will insert a {{mustache}} right there."; 
Dictionary<string, string> data = new Dictionary<string,string>(); 
data["mustache"] = "Beard"; 
string final = Render.StringToString(template, data)); 
+0

如果我能接受两个答案,我也会接受这个答案,谢谢! – MatthewMartin 2012-03-08 15:21:11

相关问题