我正在 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/