您可以在 t4 模板中使用全局变量吗? [英] Can you use global variables inside a t4 template?

查看:24
本文介绍了您可以在 t4 模板中使用全局变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 TT 文件中使用全局变量?

How can I use global variables in a TT file?

如果我在头文件中声明一个变量,如果我在函数中引用它,我会得到一个编译错误.

If I declare a variable in the header I get a compile error if I reference it in a function.

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<# 
     int ValueForThisFile = 35;

     SomeFunction();
#>

<#+
void SomeFunction() {
#>
    public void GeneratedCode() { 
        int value = <#=ValueForThisFile#>;
    }
<#+
}
#>

我知道我可以将它作为参数传递,但是有数百个调用,如果我能避免这种情况,它在语法上会更紧凑.如果这是一个文件,我可以对值进行硬编码,但有许多文件具有不同的设置和生成代码的常见包含文件.

I know that I could pass it as an argument but there are hundreds of calls and it would be syntactically tighter if I could avoid that. If this were one file I could hard code the value but there are dozens of files that have different settings and common include files that generate the code.

推荐答案

我认为这是不可能的.当 T4 解析您的模板时,它实际上是在生成一个类.所有 <# #> 内容都注入到该类的单个方法中,而所有 <#+ #> 标签作为方法添加到该类中,允许您从单个方法 <# #> 标签中调用它们.因此,ValueForThisFile"变量的范围仅限于该单个方法.举个简单的例子,这个模板:

I don't think that is possible. When T4 parses your template it is actually generating a class. All the <# #> contents are injected into a single method on that class while all <#+ #> tags are added as methods to that class, allowing you to call them from the single method <# #> tags. So the scope of the "ValueForThisFile" variable is limited to that single method. For a simple example, this template:

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<# 
     int ValueForThisFile = 35;

     SomeFunction();
#>

<#+
void SomeFunction() {
   return ValueForThisFile;
}
#>

会生成这样的类:

class T4Gen {

private void MainWork() {
    int ValueForThisFile = 35;
    this.SomeFunction();
}

private void SomeFunction{
    return ValueForThisFile;
}

}

变量ValueForThisFile"仅作用于 MainWork 函数.T4 生成的实际类要复杂得多,但正如您所见,在这样的代码中不可能有全局变量.

The variable "ValueForThisFile" is only scoped to the MainWork function. The actual class T4 generates is much more complicated but as you see there would be no way to have a global variable in code like that.

这篇关于您可以在 t4 模板中使用全局变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆