T4.错误:表达式块计算为Null



我已经添加了模板。这个文件看起来像:

<#@ 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)...

我该怎么做才能避免看到这些消息?

Thanks in advance

问题是ClassName属性为空。修复该错误的一种方法是将类特性块中的代码更改为:

<#+
    private string className = "";
    public string ClassName {
        get { return className; }
        set { className = value; }
    }
#>

我假设,您想生成类似

的内容
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";
#>

最新更新