このConsole
クラスは、SetOut
出力をカスタム ストリームに書き込むために使用できるメソッドを提供します。たとえば、StringBuilder にストリーミングして変更を監視したり、キーワードを監視するカスタム ストリーム実装を作成したりできます。
たとえば、KeywordWatcherStreamWrapper
指定されたキーワードを監視し、キーワードが検出されるたびにすべてのリスナーに対してイベントを発生させるクラスを次に示します。
public class KeywordWatcherStreamWrapper : TextWriter
{
private TextWriter underlyingStream;
private string keyword;
public event EventHandler KeywordFound;
public KeywordWatcherStreamWrapper(TextWriter underlyingStream, string keyword)
{
this.underlyingStream = underlyingStream;
this.keyword = keyword;
}
public override Encoding Encoding
{
get { return this.underlyingStream.Encoding; }
}
public override void Write(string s)
{
this.underlyingStream.Write(s);
if (s.Contains(keyword))
if (KeywordFound != null)
KeywordFound(this, EventArgs.Empty);
}
public override void WriteLine(string s)
{
this.underlyingStream.WriteLine(s);
if (s.Contains(keyword))
if (KeywordFound != null)
KeywordFound(this, EventArgs.Empty);
}
}
使用例:
var kw = new KeywordWatcherStreamWrapper(Console.Out, "Hello");
kw.KeywordFound += (s, e) => { throw new Exception("Keyword found!"); };
try {
Console.SetOut(kw);
Console.WriteLine("Testing");
Console.WriteLine("Hel");
Console.WriteLine("lo");
Console.WriteLine("Hello");
Console.WriteLine("Final");
} catch (Exception ex) { Console.Write(ex.Message); }
キーワード全体を含む2 番目のWrite
ステートメントでイベントが発生し、例外がスローされます。また、これにより基になるストリームが暗黙的にラップされ、引き続きそれに書き込まれるため、コンソール出力は引き続き通常どおり生成されることに注意してください。
出力例:
Testing
Hel
lo
Hello
Keyword found!