简体   繁体   中英

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. It would be ideal if the TransformText(); method writes to a steam instead of using 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. 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.

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). And the base class also contains other overloads of Write() , which you might need to hide as well.

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 . But you would still need to deal with all the overloads of Write() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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