c# - T4 模板和运行时参数

标签 c# visual-studio-2010 t4 template-engine

我正在 VS 2010 中构建插件,但卡在了 T4 代。 现在我已经实现了(如 MSDN 建议的那样)一个自定义 T4 主机来生成我的 T4 结果,我以这种方式使用它:

        const string content = @"c:\Simple.tt";
        var engine = new Engine();
        var host = new MyTemplateHost();            
        var result = engine.ProcessTemplate(File.ReadAllText(content), host);
        foreach (CompilerError error in host.Errors)
        {
            Console.WriteLine(error.ErrorText);
        }

这一直有效,直到我在模板中传递了一个参数。一旦我在 .tt 文件中创建了一个参数,主机就吓坏了,说它不知道如何解析它。 我看到您可以使用 TemplateSession 来做到这一点,但我不知道如何将它传递给我的主机? 是否有更好的方法使用 C# 从 .tt 生成代码并在运行时传递参数?也许我走错了路。

最佳答案

在 Visual Studio 2010 中,T4 模板引擎发生了根本性的变化。 现在您可以直接运行模板文件并向其传递您想要的任何参数类型。

        var template = Activator.CreateInstance<SimpleTemplate>();
        var session = new TextTemplatingSession();
        session["namespacename"] = "MyNamespace";
        session["classname"] = "MyClass";
        var properties = new List<CustomProperty>
        {
           new CustomProperty{ Name = "FirstProperty", ValueType = typeof(Int32) }
        };
        session["properties"] = properties;
        template.Session = session;
        template.Initialize();

此语句将处理以下模板:

<#@ template language="C#" debug="true"  #>
<#@ output extension=".cs" #>
<#@ assembly name="System.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="SampleDomain.Entities" #>
<#@ parameter name="namespacename" type="System.String" #>
<#@ parameter name="classname" type="System.String" #>
<#@ parameter name="properties" type="System.Collections.Generic.List<CustomProperty>" #>

using System;
using System.Collections.Generic;
using SampleDomain.Entities;

namespace <#= this.namespacename #>
{
public class <#= this.classname #>

所以老实说,主机不再需要......

关于c# - T4 模板和运行时参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4402011/

相关文章:

c# - gridview 分页不起作用

c# - 如果条件为真,代码不返回

c# - 生成枚举的 JavaScript 表示

c# - 在 Linux Python 中使用 .NET Core 库

c# - 这真的是一种简化吗?

.net - 这不是断点的有效位置

visual-studio-2010 - 我在 VS2010 中找不到模板 ADO.NET 实体数据模型

c++ - 错误 MSB6006 : "CL.exe" exited with code -1073741805

visual-studio-2008 - 从源代码管理中排除嵌套项

c# - 给定一个表示类型的字符串,我需要知道它是值类型还是引用类型