生成的 C# 代码中的 T4 缩进

T4 indentation in generated C# code

使用T4生成C#代码时,TABS乱七八糟,无法正确识别:

public partial class Foo : Base
{
        public int C { get; set; }
        [MappedProperty("A.B[{C}].Foo")]
    public int Foo { get; set; }
}

我使用的缩进看似正确的 .TT 代码类似于以下内容:

public partial class <#= ViewModelName #>
{
    <#  foreach(var property in ViewModelProperties) { #> 
        <# if(property.Mapping != null) { #>
        [MappedProperty("<#= property.Mapping #>")]
        <# } #>
        public <#= property.TypeDeclaration #> <#= property.MemberName #> { get; set; }
    <# } #>
}

此代码片段反映了我已经尝试做的事情:尽可能将控制语句和块放在一行中。

我喜欢这样做,从来没有遇到过任何问题。

public partial class <#= ViewModelName #>
{
<#
    foreach(var property in ViewModelProperties) { 
        if(property.Mapping != null) { 
#>
    [MappedProperty("<#= property.Mapping #>")]
<#
        }
#>
    public <#= property.TypeDeclaration #> <#= property.MemberName #> { get; set; }
<#
    }
#>
}

像这样使用PushIndent(), PopIndent() and ClearIndent()

public partial class <#= ViewModelName #>
{
<# PushIndent("   "); #>
<#  foreach(var property in ViewModelProperties) { #> 
<# if(property.Mapping != null) { #>
[MappedProperty("<#= property.Mapping #>")]
<# } #>
public <#= property.TypeDeclaration #> <#= property.MemberName #> { get; set; }
<# } #>
<# PopIndent(); #>
}

或者……

public partial class <#= ViewModelName #>
{
<# 
   PushIndent("   "); 
   foreach(var property in ViewModelProperties) {
      if(property.Mapping != null) { 
         WriteLine("[MappedProperty({0})]", property.Mapping);
      }
      WriteLine("public {0} {1} {{ get; set; }}", property.TypeDeclaration, property.MemberName);
   }
   PopIndent(); 
#>
}

您需要减少空格和“<#”的混乱,这样结果会更令人期待:

  1. 你不需要在一半的地方使用'<#',foreachif可以保持在一个范围内。这样您就可以减少标签外的潜在空格并使其更具可读性。

  2. 您的 public 行以双制表符开头,因此它会生成一个 属性 缩进双制表符而不是单个制表符。删除一个。

  3. '<#'标签外的所有空格都将被打印出来,去掉它们,只留下标签外(标签前后)必要的部分。否则它们会累积并破坏您的格式。