c# - T4 文本生成部分类

标签 c# .net t4

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

相关文章:

c# - 我可以确定给定字符串的内置哈希始终相同吗?

.net - 什么时候引发点击事件?

c# - 如果我完全使用 IocContainer,是否应该在任何地方都使用它?

c# - 相当于 Actions 和 Func 的 Tuple.Create

visual-studio - 为什么我的 T4 模板在文件名后附加一个数字?

asp.net-mvc - 如何在 VS2010 中获取 T4 以迭代类的属性

asp.net-mvc-3 - T4模板获取属性

c# - 如何释放虚拟内存?

c# - UserControl 中的 DependencyProperty bool

C# - 用分号替换换行符