T4模板中的评论

amo*_*oss 49 t4 comments

这看起来像是一个基本问题,但我无法找到答案的MSDN文章或StackOverflow问题:是否可以在T4模板中进行行注释或阻止注释?我不打算生成带注释的代码(这很容易和直接),而是注释掉我的T4标记块.那可能吗?

Gar*_*thJ 58

要将注释包含在控制代码中,它们需要位于某种代码块中

<# // Hello this is a comment #> for example
Run Code Online (Sandbox Code Playgroud)

要么

<#+ // Hello this is a comment in a class feature block #>
Run Code Online (Sandbox Code Playgroud)

如果您对输出中的额外换行敏感,有时需要将关闭标记推送到下一行.

如果你想要注释整个标记块,遗憾的是没有一个简单的解决方案,结果变得相当丑陋.

你可以通过转义你想要评论的标签来做到这一点,如下所示:

\<# my control code \#>
Run Code Online (Sandbox Code Playgroud)

然后将其放在另一个块中的注释中,如下所示:

<# // \<# my control code \#> #>
Run Code Online (Sandbox Code Playgroud)

  • T4编辑器似乎更喜欢`<#/*...*/#>`语法 - 至少对于突出显示. (11认同)

eng*_*rce 15

添加块注释的最佳方法是使用#if和#endif

<#
   #if false
   foreach(var typeName in typeNames)
   { 
       var className = typeName + "Adapter";
#>
    // ...
<#  
    }
    #endif
#>
Run Code Online (Sandbox Code Playgroud)