T4文本模板

时间:2014-06-20 08:47:56

标签: c# t4 texttemplate

我有以下.tt文件,我想用作包含文件,我想在主T4文件中公开一些属性:

Include.tt

<#@ assembly name="$(ProjectDir)bin\Debug\EPPlus.dll" #>
<#@ assembly name="System.Configuration.dll" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Configuration" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#@ import namespace="OfficeOpenXml" #>
<#
    public static string EDIInputPath
    {
        get
        {
            return ConfigurationManager.AppSettings["inputPath"];
        }
    }
#>

保存此代码时,会抛出7个编译时错误,第一个错误表示“语句预期”。

我不经常使用T4模板,所以我不完全确定我在这里做错了什么。

1 个答案:

答案 0 :(得分:2)

查看错误的最简单方法是将T4文件上的CustomTool属性更改为 TextTemplatingFilePreprocessor 。然后,您可以在Visual Studio中看到生成的代码。

在您的情况下,问题是在标准控制块内部

<# #> 

您只能拥有可在方法中使用的语句。 T4模板引擎会将这些语句放在TransformText()方法中,该方法输出模板的文本。

您已定义了方法中不允许的属性。您的属性代码需要进入类功能块:

<#+ #>