问题
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