0

在使用 Console.SetOut 将自定义 TextWriter 放在那里后,我在从控制台检索自定义 TextWriter 时遇到问题。

这是使用 StreamWriter 的简化版本:

StreamWriter sw = new(@".\log.txt");
sw.AutoFlush = true;

Console.SetOut(sw);

if (sw != Console.Out)
    Console.WriteLine("Not the same."); // but why?

if (Console.Out is StreamWriter writer)
{
    // this is not happening
}
else
{
    Console.WriteLine("Why can't I cast this back to its original type?");
}

Console.SetOut(TextWriter) 的文档说它将 Out 属性设置为以 TextWriter 对象为目标。

我正在使用 Visual Studio 2022,目标是 Net6.0。

4

0 回答 0