Inheriting from StreamWriter with smallest possible effort

女生的网名这么多〃 提交于 2019-12-12 11:26:02

问题


I am using an external library which allows logging using StreamWriter - now I want to add some handling based on the content of the logging. As I want to avoid to loop through the log file, I would like to write a class which inherits from StreamWriter.
What is the best way to inherit from StreamWriter with as few re-implementations of methods/constructors?


回答1:


I'm not sure of what you want to do exactly, but if you only want to inspect what is being written in the stream, you can do this:

public class CustomStreamWriter : StreamWriter
{
    public CustomStreamWriter(Stream stream)
        : base(stream)
    {}

    public override void Write(string value)
    {
        //Inspect the value and do something

        base.Write(value);
    }
}



回答2:


Determine the constructor the external library use and implement that (or just implement them all) and then you just need to override the write method(s) that your external library uses.

public class Class1 : StreamWriter 
{
    public Class1(Stream stream)
        : base(stream)
    {

    }
    public Class1(Stream stream, Encoding encoding)
        : base(stream, encoding)
    {

    }
    public Class1(Stream stream, Encoding encoding, int bufferSize)
        : base(stream, encoding, bufferSize)
    {

    }
    public Class1(string path)
        : base(path)
    {

    }
    public Class1(string path, bool append)
        : base(path, append)
    {

    }
    public Class1(string path, bool append, Encoding encoding)
        : base(path, append, encoding)
    {

    }
    public Class1(string path, bool append, Encoding encoding, int bufferSize)
        : base(path, append, encoding, bufferSize)
    {

    }

    public override void Write(string value)
    {
        base.Write(value);
    }
}


来源:https://stackoverflow.com/questions/2266986/inheriting-from-streamwriter-with-smallest-possible-effort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!