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

标签 c# t4

我试图让 If else 语句根据从循环传入的对象计算值。这个模板一直有效,直到我在 if else block 中添加并且它说它不能用作语句。想法??

<#@ 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# 中也可为空。

最佳答案

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 #>

关于c# - T4 模板 If Else 语句写出对象而不是文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35759324/

相关文章:

nuget - 如何从 NuGet 包中排除 T4 模板

t4 - Entity Framework 5.0 EntityObject Generator 在 Visual Studio 2012 RC 中不可用?

c# - T4 模板 : Import namespace in host assembly

c# - EF Core 有条件地启用延迟加载

c# - 在 ASP.Net Core Identity 中刷新用户 cookie 票证

c# - 使用 t4 模板在子文件夹中生成类

.net - 主机特定在 t4 模板中意味着什么?

c# - 写入值数据分割

c# - 指定的 key 太长;最大 key 长度为 767 字节 - ASPNet Identity MySQL

c# - 将字符数组转换为枚举数组?