简体   繁体   中英

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

I'm changing the Console out to a custom TextWriterclass (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).

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 . This is the reason why you get false when you check Console.Out == myWriter;

You need some reflection code to check it, because the wrapping TextWriter is internal. It is named as 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 . It wraps your text writer in a SyncTextWriter .

I think you have to use reflection to see the wrapped type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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