我正在测试 T4 文本模板生成运行时文本的功能。
在 MSDN - Run-Time Text Generation with T4它指出:
Usually a template must import some data from other parts of the application. To make this easy, the code built by the template is a partial class. You can create another part of the same class in another file in your project. That file can include a constructor with parameters, properties and functions that can accessed both by the code that is embedded in the template, and by the rest of the application.
我试过这个(VS2017 - .NET 4.6.1)并在编译时得到以下错误 -
'CSharpFunction' does not contain a definition for 'TransformText'
A namespace cannot directly contain members such as fields or methods
Compiling transformation: The name 'FunctionName' does not exist in the current context
The name 'ErrorGeneratingOutput' does not exist in the current context.
CSharpFunction.cs
partial class CSharpFunction
{
private string FunctionName;
public CSharpFunction(string functionName)
{
FunctionName = functionName;
}
}
CSharpFunction.tt
<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
public void <#=FunctionName#>()
{
Console.WriteLine("<#=FunctionName#>");
}
Program.cs
class Program
{
static void Main(string[] args)
{
var obj = new CSharpFunction("Test");
string output = obj.TransformText();
Console.WriteLine(output);
Console.ReadLine();
}
}
我错过了什么吗?
最佳答案
确保您的运行时文本模板文件的属性 Custom Tools 设置为 TextTemplatingFilePreprocessor。
这是通过创建一个运行时文本模板自动完成的,该文件类型与在 Visual Studio 中创建时的文本模板不同。
关于c# - T4 文本生成部分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51111796/