创建一个Generic方法,该方法将写入文件或写入控制台输出

时间:2015-06-19 20:21:15

标签: c# file-io console.writeline

我有两个在主体上相同的功能,一个写入文件,一个写入控制台 有没有办法使文件/控制台通用到我传递给函数的内容?

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();
}

1 个答案:

答案 0 :(得分:3)

StreamWriterTextWriterWrite*的{​​{1}}静态方法写入ConsoleConsole.OutConsole.Out。所以常见的东西&#34;写在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