【问题标题】:Create a Generic method that will write to a file or write to console output创建一个将写入文件或写入控制台输出的通用方法
【发布时间】:2015-06-19 20:21:15
【问题描述】:

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

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

【问题讨论】:

    标签: c# file-io console.writeline


    【解决方案1】:

    StreamWriterTextWriterConsoleWrite* 静态方法写入 Console.OutConsole.OutTextWriter。所以常见的“事情”是写在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

    【讨论】:

      猜你喜欢
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 2020-04-10
      • 2012-02-01
      相关资源
      最近更新 更多