T4中<#和<#+有什么区别?

Ear*_*rlz 13 .net t4

T4中的<#标签和<#+标签有什么区别?

Mar*_*off 17

文档说明:

标准控制块

标准控制块是生成输出文件一部分的程序代码的一部分.

您可以在模板文件中混合任意数量的文本块和标准控制块.但是,您不能将一个控制块放在另一个控制块内.每个标准控制块由符号分隔<# ... #>.

...

类功能控制块

类特征控制块定义不应包含在主变换中的属性,方法或任何其他代码.类特征块经常用于辅助函数.通常,类功能块放在单独的文件中,以便它们可以包含在多个文本模板中.

类特征控制块由符号分隔 <#+ ... #>

例如,以下模板文件声明并使用方法:

<#@ output extension=".txt" #>
Squares:
<#
    for(int i = 0; i < 4; i++)
    {
#>
    The square of <#= i #> is <#= Square(i+1) #>.
<#
    } 
#>
That is the end of the list.
<#+   // Start of class feature block
private int Square(int i)
{
    return i*i; 
}
#>
Run Code Online (Sandbox Code Playgroud)


Ken*_*rey 6

Reading the documentation doesn't immediately make it obvious what the difference is. They're both code that's included in your generated template.

This article archive makes it a little more clear.

To see the difference in action, create a Runtime Text Template with these contents:

<#@ template language="C#" #>
<# // STANDARD CONTROL BLOCK #>
<#+ // CLASS FEATURE BLOCK #>
Run Code Online (Sandbox Code Playgroud)

The generated class will look essentially like this:

public class Something
{
    public string TransformText()
    {
 // STANDARD CONTROL BLOCK 
        return this.GenerationEnvironment.ToString();
    }
 // CLASS FEATURE BLOCK 
}
Run Code Online (Sandbox Code Playgroud)

As you can see, standard control blocks are placed in the TransformText method, while class features are placed at the class level.