简体   繁体   English

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

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

I'm changing the Console out to a custom TextWriterclass (TextBoxStreamWriter). 我将控制台更改为自定义TextWriter类(TextBoxStreamWriter)。 I want to check if the Console.Out was set using my writer instance or not (because other class may have changed it, etc). 我想检查是否使用我的writer实例设置了Console.Out(因为其他类可能已经更改了它,等等)。

Sample: 样品:

// "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 will wrap your myWriter in a another TextWriter to make it thread safe by wrapping all the calls in a lock . Console.SetOut会将myWriter包装在另一个TextWriter ,通过将所有调用包装在lock使其线程安全。 This is the reason why you get false when you check Console.Out == myWriter; 这就是为什么当您检查Console.Out == myWriter;时会Console.Out == myWriter;

You need some reflection code to check it, because the wrapping TextWriter is internal. 您需要一些反射代码来检查它,因为包装的TextWriter是内部的。 It is named as SyncTextWriter . 它被命名为SyncTextWriter

You can refer the source here for more information. 您可以在此处参考以获取更多信息。

That's expected, look at the Console.SetOut source code: http://referencesource.microsoft.com/#mscorlib/system/console.cs,2d6029756ecc3409 . 可以预期,请查看Console.SetOut源代码: http : //referencesource.microsoft.com/#mscorlib/system/console.cs,2d6029756ecc3409 It wraps your text writer in a SyncTextWriter . 它将您的文本SyncTextWriter包装在SyncTextWriter

I think you have to use reflection to see the wrapped type. 我认为您必须使用反射来查看包装的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM