T4 模板 If Else 语句写出对象而不是文本

本文关键字:对象 文本 模板 If Else 语句 T4 | 更新日期: 2023-09-27 18:37:03

我正在尝试让 If else 语句根据从循环传入的对象计算值。这个模板一直有效,直到我添加了 if else 块,它说它不能用作语句。思潮??

<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="CookieCutterDT" #>
<#@ import namespace="CookieCutterBL.DT_Template" #>
namespace <#= NameSpace #>
{
    public class <#= ClassName #>
    {
<#
        foreach(ColumnDT c in Columns)
    {#>
        public <# if (c.IsNullable && c.DataType != "string" && c.DataType != "string []") { c.DataType + "?"; } else { c.DataType; } #> <#= c.ColumnName #> { get; set; };
<#
    }
#>
    }
}

if else 正在检查该列是否为可为空的字段,如果是,则使其数据类型在 C# 中也可为空。

T4 模板 If Else 语句写出对象而不是文本

if 的 then/else 部分中的表达式不会生成代码。你应该这样写:

public <# if (c.IsNullable && c.DataType != "string" && c.DataType != "string []") { #>
    <#= c.DataType + "?" #>
<# } else { #> 
    <#= c.DataType #>
<# } #> <#= c.ColumnName #> { get; set; };

或者,使用条件运算符?:作为较短的替代方法:

<#= (c.IsNullable && c.DataType != "string" && c.DataType != "string []") ? (c.DataType + "?") : c.DataType #>

我能够自己解决这个问题,刚刚看到一篇文章,让我想到尝试.写方法,砰它有效!!以防万一其他人遇到类似的问题。

public <# if (c.IsNullable && c.DataType != "string" && c.DataType != "string []") { this.Write(c.DataType + "?"); } else { this.Write(c.DataType); } #> <#= c.ColumnName #> { get; set; };