【问题标题】:How to create a custom partial class with T4 template? [duplicate]如何使用 T4 模板创建自定义分部类? [复制]
【发布时间】:2015-09-08 19:14:03
【问题描述】:

我想要一个模板,它以某种方式接受class_name 属性并创建一个类,其名称是class_name 的值

理想情况下,我应该能够在包含public partial class MyClass 定义的MyClass.cs 中执行我的模板,这会将class_name 设置为MyClass

这个模板

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>

public partial class <#=class_name #>
{

}

产生错误:

Error   1   Compiling transformation: The name 'class_name' does not exist in the current context

如何将class_name 的定义放入其中?

【问题讨论】:

  • 您想从您的代码 (MyClass.cs) 或 Visual Studio 中将该模板作为 .tt 文件在您的项目中执行吗?
  • 我想从 Visual Studio 执行它
  • 已经有类似的帖子here,这是你想要做的吗?
  • 是的。没注意到。谢谢。

标签: c# t4


【解决方案1】:

你可以像这样定义class_name:

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<# var class_name = "MyClass"; #>

public partial class <#=class_name #>
{

}

【讨论】:

  • 这并不是真正的传递参数,它只是在这个模板的上下文中设置了一个局部变量
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-21
相关资源
最近更新 更多