我可以从C#以编程方式使用T4吗?

我正在编写生成C#代码的软件。 主要是我使用StringTemplate和StringBuilder。

有没有办法直接从我的代码中使用T4模板?

Oleg Sych在此处描述了如何执行此操作: 了解T4:预处理文本模板 。 请注意,您似乎需要Visual Studio 2010来生成预处理的文本模板,但您可以在任何地方托管预处理的文本模板 – 包括在WinForms应用程序中。

一个简单的方法:

System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents = false; // Set text transform program (this could change according to the Windows version) proc.StartInfo.FileName = "C:\\Program Files (x86)\\Common Files\\microsoft shared\\TextTemplating\\10.0\\TextTransform.exe"; // Specify T4 template file proc.StartInfo.Arguments = "C:\template.tt"; proc.Start();