Home   Cover Cover Cover Cover
 

Delegates mit Zustand

A04.cs
using System;
using System.IO;

delegate void LogWriter(string message);

class Logger {
  StreamWriter w;
  
  public Logger(string path) {
    w = File.CreateText(path);
  }
  
  public void Print(string msg) {
    w.WriteLine(msg);
  }
  
  public void Flush() {
    w.Flush();
  }
  
  public void Close() {
    w.Close();
  }
}

class Test {
  static LogWriter Log;
  
  static void Print(string s) {
    Console.WriteLine(s);
  }
  
  static void Main(string[] arg) {
    Logger x = new Logger("log.txt");
    Log += new LogWriter(Print);
    Log += new LogWriter(x.Print);
    Log("one");
    Log("two");
    Log("three");
    x.Flush();
    x.Close();
  }
  
}