我正在尝试实现一个可以处理 T4 模板的应用程序。
我已经实现了一个自定义文本模板主机,如本文所示: https://msdn.microsoft.com/en-us/library/bb126579.aspx
我可以像这样运行一个简单的模板,它可以很好地处理 C# 代码和 include 指令:
<#@ template debug="true" #>
<#@ include file="includehello.txt" #>
Some text.
<# for(int i = 0; i < 3; i++) { #>
//Line <#= i #>
<# } #>
但是,一旦我尝试使用“参数”指令,我就会收到 NullReferenceException。
<#@ template debug="true" #>
<#@ parameter type="System.String" name="worldParam" #>
Hello <#=worldParam#>
运行模板的代码如下所示:
CustomCmdLineHost host = new CustomCmdLineHost();
Engine engine = new Engine();
host.TemplateFileValue = "HelloWorldTemplate.tt";
//Read the text template.
string input = File.ReadAllText(templateFileName);
host.Session = host.CreateSession();
// Add parameter values to the Session:
host.Session["worldParam"] = "world";
//Transform the text template.
string output = engine.ProcessTemplate(input, host);
//Save the result
string outputFileName = Path.GetFileNameWithoutExtension(templateFileName);
outputFileName = Path.Combine(Path.GetDirectoryName(templateFileName), outputFileName);
outputFileName = outputFileName + "1" + host.FileExtension;
File.WriteAllText(outputFileName, output, host.FileEncoding);
我怀疑参数值从未传输到引擎中,所以问题是:
如何将参数值传输到引擎?
我找到了 this question使用host.Initialize();
但这似乎是针对预编译模板和 Initialize
方法未在示例文章中实现。 CreateSession();
也不是我按照那篇文章中的描述实现了它。
附言
为了让文章中的代码正常工作,我必须添加 Nuget 包 Microsoft.CodeAnalysis
, 除了将提到的引用添加到 Microsoft.VisualStudio.TextTemplating.15.0
和 Microsoft.VisualStudio.TextTemplating.Interfaces.15.0
.
我正在使用 VS2017。目标框架:.Net Framework 4.6.2
最佳答案
除了ITextTemplatingEngineHost
,您还需要实现ITextTemplatingSessionHost
接口(interface)。类签名必须是
public class CustomCmdLineHost : ITextTemplatingEngineHost, ITextTemplatingSessionHost
关于c# - 使用参数指令时 T4 模板 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47163466/