c# - System.Diagnostics.Debug 类是否有 TextWriter 接口(interface)?

标签 c# .net

我经常对 System.Diagnostics.Debug.Write/WriteLine 方法感到沮丧。我想使用 TextWriter 类熟悉的 Write/WriteLine 方法,所以我经常写

Debug.WriteLine("# entries {0} for connection {1}", countOfEntries, connection);

这会导致编译器错误。我写完了

Debug.WriteLine(string.Format("# entries {0} for connection {1}", 
    countOfEntries, connection));

这真的很尴尬。

CLR 是否有一个派生自 TextWriter 的类来“包装”System.Debug,还是我应该自己推出?

最佳答案

函数Debug.Print允许您使用格式和参数。

如果您更喜欢使用 TextWriter 接口(interface),请使用以下包装器类:

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();
    };
}

关于c# - System.Diagnostics.Debug 类是否有 TextWriter 接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2779746/

相关文章:

.net - 使用 X509Certificate2 和 ECC 公钥加载证书

c# - 如何从 .NET 将文件上传到一个驱动器

c# - 0u在c#中是什么意思?

c# - 从 HttpContext.User.Claims 中提取值

c# - 有没有办法从使用 C# 阻止文件的进程中获取 PID?

c# - 如何检查 Access 数据库表中是否存在特定列

c# - .Net 扩展方法与实用程序类

.net - 以下正则表达式模式如何工作?

c# - 如何从缓存中清除过期的项目?

c# - .NET XmlSerializer 和小数