如何使用我的 TextWriter 检查是否设置了 Console.Out

How to check if Console.Out was set using my TextWriter

我正在将控制台更改为自定义 TextWriterclass (TextBoxStreamWriter)。我想检查 Console.Out 是否是使用我的编写器实例设置的(因为其他 class 可能已经更改了它,等等)。

样本:

// "TextBoxStreamWriter : TextWriter" is a custom class that writes to a textbox...
TextBoxStreamWriter myWriter = new TextBoxStreamWriter(someTextBoxInstance);
Console.SetOut(myWriter);
bool check = Console.Out == myWriter;
// But check is false! I need to know if .Out was set from my custom class or not.

Console.SetOut 会将您的 myWriter 包装在另一个 TextWriter 中,通过将所有调用包装在 lock 中使其线程安全。这就是为什么你在检查 Console.Out == myWriter;

时得到 false 的原因

您需要一些反射代码来检查它,因为包装 TextWriter 是内部的。它被命名为 SyncTextWriter.

您可以参考source here了解更多信息。

这是意料之中的,请查看 Console.SetOut 源代码:http://referencesource.microsoft.com/#mscorlib/system/console.cs,2d6029756ecc3409。它将您的文本编写器包装在 SyncTextWriter.

我认为你必须使用反射才能看到包装类型。