创建一个将写入文件或写入控制台输出的泛型方法

本文关键字:控制台 输出 泛型方法 文件 一个 创建 | 更新日期: 2023-09-27 17:57:06

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

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

创建一个将写入文件或写入控制台输出的泛型方法

StreamWriter是一个TextWriterWrite*静态方法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