C# 如何将字符串参数传递给t4模板
嗨,我正在试图找到一种方法,将普通字符串作为参数传递给文本模板 这是我的模板代码,如果有人能告诉我需要用c编写什么来传递参数和创建类文件。那会很有帮助的,谢谢C# 如何将字符串参数传递给t4模板,c#,string,parameters,t4,texttemplate,C#,String,Parameters,T4,Texttemplate,嗨,我正在试图找到一种方法,将普通字符串作为参数传递给文本模板 这是我的模板代码,如果有人能告诉我需要用c编写什么来传递参数和创建类文件。那会很有帮助的,谢谢 <#@ template debug="false" hostspecific="true" language="C#" #> <#@ output extension=".cs" #> <#@ assembly name="System.Xml" #> <#@ assembly name="En
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ parameter name="namespacename" type="System.String" #>
<#@ parameter name="classname" type="System.String" #>
<#
this.OutputInfo.File(this.classname);
#>
namespace <#= this.namespacename #>
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
/// <summary>
/// This class describes the data layer related to <#= this.classname #>.
/// </summary>
/// <history>
/// <change author=`Auto Generated` date=<#= DateTime.Now.ToString("dd/MM/yyyy") #>>Original Version</change>
/// </history>
public partial class <#= this.classname #> : DataObject
{
#region constructor
/// <summary>
/// A constructor which allows the base constructor to attempt to extract the connection string from the config file.
/// </summary>
public <#= this.classname #>() : base() {}
/// <summary>
/// A constructor which delegates to the base constructor to enable use of connection string.
/// </summary>
/// <param name='connectionstring`></param>
public <#= this.classname #>(string connectionstring) : base(connectionstring) {}
#endregion
}
}
以下是传递参数的一种方法: 您必须创建TextTemplatingSession。 为参数设置会话字典。 使用该会话处理模板。 示例代码将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); #>
我在OlegSych的博客上看到了这一点,这是t4的重要资源。这里是更新的链接:这是一个3年前的问题,我不知道模板库有多大的发展,我的解决方案是否适用于Visual Studio和/或.NET等旧版本。我目前正在使用Visual Studio 2015和.NET 4.6.1 总结 使用类功能控制块向模板的生成类声明公共成员,并在模板文本中引用这些公共成员 实例 在C项目中,选择AddNewItem>Runtime Text Template>Sallation.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 Alice.
My name is Bob.
I am 38 years old.
Press any key to continue . . .
有关T4语法的更多信息,请参阅MSDN文章。也可以在处理模板内容之前将参数注入模板内容。 为此,将其添加到模板中作为代码注入的占位符 GenericClass.t包括: 然后在任何特定模板中使用它,您只需传递必要的参数UInt64Class.Generated.tt:
完整的例子可以在@Rice上找到,它仍然适用于我。刚刚在VS2017的一个新控制台项目中尝试了我的示例的确切步骤。新项目>Visual C>Windows经典桌面>使用.NET 4.7.1的控制台应用程序.NET Framework。T4仍然受到支持。也许你在尝试一个.NET核心项目。我认为T4在Core中不受支持。但是我个人在过去的几个月里已经换了工作,我对此感到非常高兴。你应该试试看!它也可以与Core一起工作。链接似乎被打断了他移动了他的网站这里是wayback机器的链接:
<#+
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 . . .
<#@ template language="C#" #>
<##>
namespace <#= Namespace #>
{
public class <#= ClassName #> : IGeneric<<#= TypeParameter #>>
{
public <#= TypeParameter #> ReturnResult() => 1 + 3;
}
}
<#+
public string ClassName { get; set; }
public string Namespace { get; set; }
public string TypeParameter { get; set; }
#>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#+
public const string ParametersInjectionPattern = "<" + "#" + "#" + ">";
public void Generate(string baseTemplatePath, IDictionary<string, string> parameters)
{
var template = File.ReadAllText(this.Host.ResolvePath(baseTemplatePath));
template = template.Replace(ParametersInjectionPattern, GenerateParametersAssignmentControlBlock(parameters));
this.Write(new Engine().ProcessTemplate(template, this.Host).Trim());
}
public string GenerateParametersAssignmentControlBlock(IDictionary<string, string> parameters)
{
var sb = new StringBuilder();
sb.Append('<').Append('#').Append(' ');
foreach (var parameter in parameters)
sb.Append($"{parameter.Key} = {parameter.Value};");
sb.Append(' ').Append('#').Append('>');
return sb.ToString();
}
public string SurroundWithQuotes(string str)
{
return $"\"{str}\"";
}
public string GetTemplateName()
{
return Path.GetFileNameWithoutExtension(this.Host.TemplateFile).Replace(".Generated", "");
}
#>
<#@ template hostspecific="true" language="C#" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<#@ include file="Generator.ttinclude" #>
<#
var parameters = new Dictionary<string, string>()
{
{ "Namespace", SurroundWithQuotes("T4GenericsExample") },
{ "ClassName", SurroundWithQuotes(GetTemplateName()) },
{ "TypeParameter", SurroundWithQuotes("System.UInt64") }
};
Generate("GenericClass.ttinclude", parameters);
#>