Is there a TextWriter interface to the System.Diagnostics.Debug class?

前端 未结 4 1608
伪装坚强ぢ
伪装坚强ぢ 2020-12-30 22:16

I\'m often frustrated by the System.Diagnostics.Debug.Write/WriteLine methods. I would like to use the Write/WriteLine methods familiar from the TextWriter class, so I ofte

4条回答
  •  执笔经年
    2020-12-30 23:10

    The function Debug.Print lets you use formatting and arguments.

    If you'd prefer to use a TextWriter interface, use the following wrapper class:

    public class DebugTextWriter : StreamWriter
    {
        public DebugTextWriter()
            : base(new DebugOutStream(), Encoding.Unicode, 1024)
        {
            this.AutoFlush = true;
        }
    
        sealed class DebugOutStream : Stream
        {
            public override void Write(byte[] buffer, int offset, int count)
            {
                Debug.Write(Encoding.Unicode.GetString(buffer, offset, count));
            }
    
            public override bool CanRead => false;
            public override bool CanSeek => false;
            public override bool CanWrite => true;
            public override void Flush() => Debug.Flush();
    
            public override long Length => throw bad_op;
            public override int Read(byte[] buffer, int offset, int count) => throw bad_op;
            public override long Seek(long offset, SeekOrigin origin) => throw bad_op;
            public override void SetLength(long value) => throw bad_op;
            public override long Position
            {
                get => throw bad_op;
                set => throw bad_op;
            }
    
            static InvalidOperationException bad_op => new InvalidOperationException();
        };
    }
    

提交回复
热议问题