c# - 使用参数指令时 T4 模板 NullReferenceException

标签 c# visual-studio-2017 t4

我正在尝试实现一个可以处理 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.0Microsoft.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/

相关文章:

c# - 如何处理这种树遍历

c# - 多线程还是不多线程?

c# - 通过等待任务或访问其 Exception 属性未观察到任务的异常

c++ - 我可以从这个回溯中找到导致崩溃的代码行吗?

.net - .tt 文件的语法高亮显示?

entity-framework - 将我的模板添加到 Studio 2010 中的代码生成项列表

c# - 更新 ListView、ObservableCollection

c++ - 如何使用 __LINE__ 或其他方法从调用站点获取行号?

c# - 如何让代码生成遵循我的格式设置?

c++ - 如何在 Visual Studio 2017 中的类型后禁用 * 的自动间距?