gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:14:01 26 4
gpt4 key购买 nike

我经常对 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com