2015-06-19 106 views
2

我有兩個在主體中相同的函數,一個寫入文件並且一個寫入控制檯。
有沒有辦法讓文件/控制檯通用到我傳遞給函數?創建將寫入文件或寫入控制檯輸出的通用方法

public void WatchWindow() 
{ 

    var max = _colLengths.Max(); 
    for (var rowIndex = 0; rowIndex < max; ++rowIndex) 
    { 
     for (var colIndex = 0; colIndex < WindowWidth; ++colIndex) 
     { 
      if (rowIndex < _colLengths[colIndex]) 
       Console.Write("{0} ", _actualWindow[colIndex]rowIndex].SymbolName); 
      else 
       Console.Write(" "); 
     } 
     Console.WriteLine(); 
    } 
    Console.WriteLine(); 
} 

public void PrintWindow(StreamWriter file) 
{ 

    var max = _colLengths.Max(); 
    for (var rowIndex = 0; rowIndex < max; ++rowIndex) 
    { 
     for (var colIndex = 0; colIndex < WindowWidth; ++colIndex) 
     { 
      if (rowIndex < _colLengths[colIndex]) 
       file.Write("{0} ", _actualWindow[colIndex][rowIndex].SymbolName); 
      else 
       file.Write(" "); 
     } 
     file.WriteLine(); 
    } 
    file.WriteLine(); 
} 

回答

3

A StreamWriterTextWriter。將Write*的靜態方法Console寫入Console.OutConsole.Out是一個TextWriter。所以常見的「東西」是寫在TextWriter

public void WriteToFile(StreamWriter file) 
{ 
    PrintWindow(file); 
} 

public void WriteToConsole() 
{ 
    PrintWindow(Console.Out); 
} 

public void PrintWindow(TextWriter writer) 
{ 

    var max = _colLengths.Max(); 
    for (var rowIndex = 0; rowIndex < max; ++rowIndex) 
    { 
     for (var colIndex = 0; colIndex < WindowWidth; ++colIndex) 
     { 
      if (rowIndex < _colLengths[colIndex]) 
       writer.Write("{0} ", _actualWindow[colIndex][rowIndex].SymbolName); 
      else 
       writer.Write(" "); 
     } 
     writer.WriteLine(); 
    } 
    writer.WriteLine(); 
} 

您可以使用WriteToFile/WriteToConsole方法(或直接在PrintWindow方法,我會重命名爲更容易,就像WriteToTextWriter

+0

這個偉大工程的感謝。 – user3281977