简体   繁体   English

如何在t4预处理模板中使用流而不是stringbuilder

[英]how can i use streams instead of stringbuilder in t4 preprocessed template

I like to generate a huge amount of text with a preprocessed T4 template. 我喜欢使用预处理的T4模板生成大量文本。 It would be ideal if the TransformText(); 如果TransformText();那将是理想的; method writes to a steam instead of using System.Text.StringBuilder GenerationEnvironment; 方法写入steam而不是使用System.Text.StringBuilder GenerationEnvironment; in the base class. 在基类中。

Does anybody know how to override this behaviour? 有人知道如何覆盖这种行为吗?

There doesn't seem to be any intended extension point in the generated code that would allow you to do that. 在生成的代码中似乎没有任何预期的扩展点可以允许您这样做。 But if you look at the generated code, it looks something like this: 但是如果你看一下生成的代码,它看起来像这样:

public partial class PreTextTemplate : PreTextTemplateBase
{
    public virtual string TransformText()
    {
        this.Write("some text");
        return this.GenerationEnvironment.ToString();
    }
}

public class PreTextTemplateBase
{
    protected StringBuilder GenerationEnvironment { get { … } set { … } }

    public void Write(string textToAppend)
    {
        // code to write to GenerationEnvironment
    }
}

It's clear that the call to this.Write() is intended to call the Write() method from the base class. 很明显,对this.Write()的调用旨在从基类调用Write()方法。 But it doesn't have to call that method, you can hide it in your non-generated part of the class: 但它不必调用该方法,您可以将其隐藏在类的非生成部分中:

public partial class PreTextTemplate
{
    private readonly StreamWriter m_streamWriter;

    public PreTextTemplate(StreamWriter streamWriter)
    {
        m_streamWriter = streamWriter;
    }

    public new void Write(string text)
    {
        m_streamWriter.Write(text);
    }
}

If you do this, the call to TransformText() will actually write to the StreamWriter , which is exactly what you want. 如果你这样做,对TransformText()的调用将实际写入StreamWriter ,这正是你想要的。

In reality, your code for the Write() method might be more complicated, to mirror what the generated Write() does (mostly related to indenting the generated text). 实际上, Write()方法的代码可能更复杂,以反映生成的Write()所做的事情(主要与缩进生成的文本有关)。 And the base class also contains other overloads of Write() , which you might need to hide as well. 基类还包含Write()其他重载,您可能也需要隐藏它们。

Alternatively, if you don't want to mirror the code in the generated Write() , you could call base.Write() in your Write() , write the content of the StringWriter to your stream and then clear the StringWriter . 另外,如果你不想反映在生成的代码Write()你可以调用base.Write()在你Write()写的内容StringWriter您的信息流,然后清除StringWriter But you would still need to deal with all the overloads of Write() . 但是你仍然需要处理Write()所有重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM