我有两个主体相同的函数,一个写入文件,一个写入控制台。
有没有办法使文件/控制台与我传递给函数的内容通用?
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
是一个 TextWriter
。 Console
的 Write*
静态方法写入 Console.Out
。 Console.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
)
关于c# - 创建一个将写入文件或写入控制台输出的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30946648/