c# - Implementing a Derived Class of TextWriter -
i have 2 classes, none of can change in way:
class 1: takes textwriter
constructor parameter , uses output stream.
class 2: provides method writeline(string)
.
i need adapter, such output of class1 written class2. therefore started adapter extends textwriter
, buffers incoming text, flushing class2 instance new line arrives.
however, there many , more methods in textwriter - should implement? output in class1 string only.
according msdn 1 should override write(char) minimum, however, enforces me \r\n new line handling myself well...
q1: know of better way reach goal? q2: if no, textwriter methods should override have minimum implementation effort.
implementing write(char)
on textwriter
derived class need do. if calls writeline
on new class, base class writeline
method called. right thing: call write
method individual \r
, \n
characters.
actually, writeline(string)
looks this:
void writeline(string s) { write(s); write("\r\n"); }
and write(string)
is, in effect:
foreach (char c in s) { write(c); }
all of write
methods in textwriter
resolve calls write(char)
in loop.
you don't have implement else. override write(char)
, plug in. work.
you can override other methods. doing make class little more efficient (faster). it's not required. simplest thing can. then, if determine after profiling custom writer slow, override other methods necessary.
here's minimal textwriter
descendant:
public class consoletextwriter: textwriter { public override void write(char value) { console.write(value); } public override encoding encoding { { return encoding.default; } } }
if write:
using (var mywriter = new consoletextwriter()) { mywriter.write("hello, world"); mywriter.writeline(); mywriter.writeline(); mywriter.writeline("goodbye cruel world."); mywriter.write("fee fie foe foo!"); }
the output is:
hello, world goodbye cruel world. fee fie foe foo!
Comments
Post a Comment