如何将字符串参数传递给t4模板

嗨,我想找到一种方法将普通字符串作为参数传递给文本模板。

这是我的模板代码,如果有人能告诉我在c#中需要写什么来传递我的参数并创建类文件。 那将是非常有帮助的,谢谢。

         namespace  { using System; using System.Collections.Generic; using System.Linq; using System.Xml; ///  /// This class describes the data layer related to . ///  ///  /// <change author=`Auto Generated` date=>Original Version ///  public partial class  : DataObject { #region constructor ///  /// A constructor which allows the base constructor to attempt to extract the connection string from the config file. ///  public () : base() {} ///  /// A constructor which delegates to the base constructor to enable use of connection string. ///  ///  public (string connectionstring) : base(connectionstring) {} #endregion } } 

以下是传递参数的一种方法:

  1. 您必须创建TextTemplatingSession。
  2. 设置参数的会话字典。
  3. 使用该会话处理模板。

示例代码(将ResolvePath替换为您的tt文件的位置):

 <#@ template debug="true" hostspecific="true" language="C#" #> <#@ output extension=".txt" #> <#@ import namespace="System.IO" #> <#@ import namespace="Microsoft.VisualStudio.TextTemplating" #> <# string templateFile = this.Host.ResolvePath("ClassGeneration.tt"); string templateContent = File.ReadAllText(templateFile); TextTemplatingSession session = new TextTemplatingSession(); session["namespacename"] = "MyNamespace1"; session["classname"] = "MyClassName"; var sessionHost = (ITextTemplatingSessionHost) this.Host; sessionHost.Session = session; Engine engine = new Engine(); string generatedContent = engine.ProcessTemplate(templateContent, this.Host); this.Write(generatedContent); #> 

我在Oleg Sych的博客上看到了这个例子 ,这是t4的重要资源。

这是一个3年前的问题,我不知道模板库已经发展了多少,以及我的问题解决方案是否适用于旧版本的Visual Studio和/或.NET等。我目前正在使用Visual Studio 2015和.NET 4.6.1。

摘要

使用“类function控制块”将公共成员声明为模板的生成类,并在模板文本中引用这些公共成员。

在C#项目中,选择Add New Item> Runtime Text Template>“Salutation.tt”。 您将获得一个带有以下默认声明的新.tt文件:

 <#@ template language="C#" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> 

在声明下方输入您的模板文本:

 My name is <#= Name #>. <# if (RevealAge) { #> I am <#= Age #> years old. <# } #> 

在.tt文件的末尾,将参数作为公共类成员添加到“类function控制块”中。 该块必须到文件末尾

 <#+ public string Name { get; set; } public int Age { get; set; } public bool RevealAge = false; #> 

然后,例如,在控制台应用程序中,您可以按如下方式使用模板:

 Console.Write(new Salutation { Name = "Alice", Age = 35, RevealAge = false }.TransformText()); Console.Write(new Salutation { Name = "Bob", Age = 38, RevealAge = true }.TransformText()); 

并获得以下输出:

 My name is Alice. My name is Bob. I am 38 years old. Press any key to continue . . . 

有关T4语法的详细信息,请参阅MSDN文章编写T4文本模板 。