加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:00:42 所属栏目:百科 来源:网络整理
导读:Web上是否有可用于从模板生成字符串的工具,我正在寻找类似于Razor的东西. 字符串应该能够在运行时生成,并且不依赖于Visual Studio(如T4).框架应该在Silverlight中工作. RazorEngine是一个满足requeriments的框架,但在Silverlight中不起作用. 提前致谢. 解决
Web上是否有可用于从模板生成字符串的工具,我正在寻找类似于Razor的东西.

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

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

提前致谢.

解决方法

希望我理解你的要求,但我认为你也可以让T4在SL工作.可以要求T4生成有时称为运行时模板的内容.我已经定义了我的模板(非常简单)并将其添加到我的Silverlight项目中.
<#
    for (var iter = 0; iter < 10; ++iter)
    {
#>
    This is just a test: #<#=iter#>
<#
    }
#>

通常它会生成如下输出:

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

但在这种情况下,我喜欢生成生成该输出的代码,即运行时模板.为此,我将自定义工具切换为: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>
    {

    }

}

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

var runtimeTemplate = new MyRuntimeTemplate();
string output = runtimeTemplate.TransformText();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读