T4. 错误:表达式块评估为 Null

3
我已添加了一个名为template.tt的文件,其内容如下:

<#@ template language="C#" debug="true" #>
<#@ output extension=".cs" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Collections.Generic" #>

using System;
using System.Collections.Generic;

namespace Test
{
    public class <#= this.ClassName#>
    {       

    }
}

<#+
    public string ClassName { get; set; }
#>

我收到了错误消息:

An expression block evaluated as Null
at Microsoft.VisualStudio.TextTemplating.ToStringHelper.ToStringWithCulture(Object objectToConvert)...

我应该怎样才能避免看到这些信息?提前感谢。
2个回答

4
问题在于ClassName属性为空。修复该错误的一种方法是更改类功能块中的代码为:
<#+
    private string className = "";

    public string ClassName {
        get { return className; }
        set { className = value; }
    }
#>

1
总的来说,在 T4 模板中,属性并没有比成员变量增加太多价值。我会完全跳过属性,直接调用成员变量“ClassName”。在创建非可重用代码的模板时,我认为有必要重新评估一些日常编码规则的价值。虽然你正在使用 C# 编写代码,但更应该将其视为脚本环境。 - GarethJ

3
我假设您想生成类似下面的内容:

我假设,您想生成类似下面的内容:

using System;
using System.Collections.Generic;

namespace Test
{
    public class MyClass
    {       

    }
}

代码中的问题在于,您在表达式块中引用了一个变量<#= this.ClassName#>,但该变量在类特征块中不存在。请按照以下方式修改代码。

<#@ template language="C#" debug="true" #>
<#@ output extension=".cs" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Collections.Generic" #>

using System;
using System.Collections.Generic;

namespace Test
{
    public class <#= this.ClassName #> //Expression Block
    {       
    }
}

<#+ //Class feature block
    public string ClassName = "MyClass";
#>

1
实际上,它作为一个属性存在,但其值为null,因为它尚未被初始化。 - GarethJ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接