用于在运行时生成字符串的文本模板(如Razor或T4)

Ari*_*iel 7 c# silverlight t4 razor

网络上是否有可用于从模板生成字符串的工具,我正在寻找类似于Razor的东西.

字符串应该能够在运行时生成,并且不依赖于Visual Studio(如T4).框架应该在Silverlight中工作.

RazorEngine是一个符合requeriments的框架,但在Silverlight中不起作用.

提前致谢.

Jus*_*mer 6

希望我理解你的要求,但我认为你也可以让T4在SL工作.可以要求T4生成有时称为运行时模板的内容.我已经定义了我的模板(非常简单)并将其添加到我的Silverlight项目中.

<#
    for (var iter = 0; iter < 10; ++iter)
    {
#>
    This is just a test: #<#=iter#>
<#
    }
#>
Run Code Online (Sandbox Code Playgroud)

通常它会生成如下输出:

This is just a test: #0
This is just a test: #1
This is just a test: #2
This is just a test: #3
This is just a test: #4
This is just a test: #5
This is just a test: #6
This is just a test: #7
This is just a test: #8
This is just a test: #9
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,我喜欢生成生成该输出的代码,即运行时模板.为此,我将自定义工具切换为:TextTemplatingFilePreprocessor

现在模板生成生成该输出的代码.如果您不清楚hostspecific = true,则不会获得Visual Studio依赖项.通过使用成员变量扩展partial类并从模板文件中引用它们,您可以在运行时修改模板上的行为.

Silverlight中的问题是silverlight缺少类:System.CodeDom.Compiler.CompilerError和System.CodeDom.Compiler.CompilerErrorCollection.

我通过为此创建自己的类来解决这个问题(仅用于此目的):

namespace System.CodeDom.Compiler
{
    public class CompilerError
    {
        public string ErrorText;
        public bool IsWarning;
    }

    public class CompilerErrorCollection : List<CompilerError>
    {

    }

}
Run Code Online (Sandbox Code Playgroud)

现在我的模板编译,我只是从我的Silverlight应用程序中生成输出:

var runtimeTemplate = new MyRuntimeTemplate();
string output = runtimeTemplate.TransformText();
Run Code Online (Sandbox Code Playgroud)