T4 模板:命名空间错误

T4 templates: Error on namespace

我正在尝试在 T4 模板中编写 class。它给出了错误:

Compiling transofrmation: Type of namespace definition, or end-of-file expected

如果我有以下代码:

<#+
namespace Learn {
    public class Converter
    {

    }
}
#>

但是如果我删除命名空间就可以正常工作

<#+
    public class Converter
    {

    }
#>

我的问题是,为什么 T4 无法识别 namespace

<#+ #> 是一个 class 特征块。您放入此块中的任何内容都将写入 class 语句中。当您添加命名空间时,T4 将生成并尝试编译如下内容:

class MyT4TempGen {

     public string run() {
          inside here is code that uses a string builder to build up all your <# #> tags into one big statement
     }

     from here down all your <#+ #> tags are added

     namespace Learn {
        public class Converter {

        }
     } 

}

这不是有效的 C# 代码,命名空间不能存在于 class 语句中。当你在没有命名空间的情况下这样做时,你会得到这个:

class MyT4TempGen {

     public string run() {
         inside here is code that uses a string builder to build up all your <# #> tags into one big statement
     }

     from here down all your <#+ #> tags are added         

     public class Converter {

     }

}

这是有效的 c# 代码,您的 class 将是 T4 编译器创建的代码的子 class。

这里有一个 link 到 msdn docs 解释支持的标签。请参阅 "Class feature control blocks" 部分。请记住,无论您在 tt 或 t4 文件中键入什么,都将被解析并转换为 .net 代码,因此您必须遵循所有正常的语法规则。