首页 > 解决方案 > 字节失败的自定义 DebuggerDisplayAttribute 为 0

问题描述

我想在 Visual Studio Code 调试器中以 0x00 格式显示字节。

我尝试了以下方法:

[assembly: DebuggerDisplay("0x{m_value.ToString(\"X2\"),nq}", Target = typeof(byte))]

它适用于字节值非零的情况。

该数组new byte[] { 0xDF, 0x86, 0x41, 0xA8, 0x00 }在调试器中显示为:

在此处输入图像描述

鉴于这y"0x00"之后:

byte x = 0x00; 
var y = $"0x{x:X2}";

我对发生了什么感到困惑?

非常感谢人们可以提供的任何帮助。

更新

这不是我的目标,但它已经足够好了,而且不太老套。我已经使用DebuggerTypeProxy了一个简单的视图类bytebyte[]它显示为:

在此处输入图像描述

标签: c#visual-studio-code

解决方案


我提出的能够很好地实现我想要的解决方案是利用DebuggerTypeProxy属性而不是DebuggerDisplay属性。

我使用了以下内容:

[assembly: DebuggerTypeProxy(typeof(ByteArrayHexView), Target = typeof(byte[]))]
[assembly: DebuggerTypeProxy(typeof(ByteHexView), Target = typeof(byte))]

public class ByteArrayHexView
{
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private byte[] array;

    public string Hex => String.Join(", ", array.Select(x => $"0x{x:X2}"));

    public ByteArrayHexView(byte[] array)
    {
        this.array = array;
    }
}

public class ByteHexView
{
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private byte value;

    public string Hex => $"0x{value:X2}";

    public ByteHexView(byte value)
    {
        this.value = value;
    }
}

推荐阅读