c# - 为什么我无法访问 T4 模板中类成员中的实用方法?

标签 c# .net t4

我正在尝试在使用 Text Template Utility Methods 的 T4 模板中编写一个类(如 WriteLine、PushIndent、PopIndent)。但是,如果我尝试在我的类中调用这些方法,我将收到一个编译器错误,指出

Compiling transformation: Cannot access a non-static member of outer type 'Microsoft.VisualStudio.TextTemplating.TextTransformation' via nested type 'Microsoft.VisualStudio.TextTemplatingBF13B4A5FBA992E5EF81A8A7A4EACCAC3F7698E169D0F7825ED4F22A28C7C52C2B766D83F4C5ACA13E0DE0B3152B6D966E34EB8C5FC677E145F55BE0485406EC.GeneratedTextTransformation.ClassGenerator'

MCVE(最小的完整可验证示例)如下所示:

<#+
public void FunctionSample()
{
    WriteLine("Hello"); // This works fine
}

public class SampleClass
{
    public static void StaticMethodSample()
    {
        WriteLine("Hello"); // This does not compile
    }

    public void InstanceMethodSample()
    {
        WriteLine("Hello"); // This does not compile either
    }
}
#>

有什么方法可以在类范围内访问这些实用方法,还是我必须使用自由函数?

(我在 Visual Studio 2015 社区上运行)

最佳答案

作为PetSerAl在评论中指出,您可以在类功能控制 block 中的任何“自由函数”中调用 T4 实用方法,因为它们是从 TextTransformation 基类继承的,即这些自由函数不完全是免费,它们是派生自 TextTransformation 的隐式创建类范围内的方法。这就是为什么您还可以在这些函数中访问 this

因此,如果您想在 T4 模板中定义的另一个类中使用实用方法(该类实际上是一个嵌套子类),您必须将 TextTransformation 的引用传递给它,例如像这样:

<#
var @object = new SampleClass(this); // Pass 'this' (TextTransformation) to the constructor
@object.SayHello();
#>

<#+
public class SampleClass // This is actually a nested child class in T4 templates
{
    private readonly TextTransformation _writer;

    public SampleClass(TextTransformation writer)
    {
        if (writer == null) throw new ArgumentNullException("writer");
        _writer = writer;
    }

    public void SayHello()
    {
        _writer.WriteLine("Hello");
    }
}
#>

更多信息可以在 MSDN library 中找到.

关于c# - 为什么我无法访问 T4 模板中类成员中的实用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33651252/

相关文章:

c# - 将列表值传递给 t4 模板

c# - Visual Studio 2005 Express 在哪里?

c# - 如何在不从 Visual Studio 中运行的情况下在本地运行 Azure worker 角色

c# - 将 WPF 中的图像源绑定(bind)到 Url

javascript - 在两个方向上动态加载用户控件

c# - 为什么字符串是密封的

c# - 在 Xamarin Forms 应用程序中获取当前页面名称

c# - 在 WPF 中验证多个链接的数据绑定(bind) TextBox 值

asp.net-mvc - MVC T4 MvcTextTemplateHost和自定义的“ Controller ” T4模板

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