如何为自定义类型使用 Visual Studio 文本可视化工具?

How to use Visual Studio Text Visualizer for custom types?

在 Visual Studio 2015(以及一些旧版本)中调试 C# 代码时,可以在各种可视化工具中显示 string 变量的值(文本、XML、HTML, JSON) 通过带有放大镜图标的下拉列表。这也适用于某些非字符串类型,例如 System.Xml.Linq.XElement。是否可以使用这些内置的可视化工具来显示我自己的自定义类型的变量值?

上下文:

我需要能够快速检查只有在 多行 文本环境中才能可接受地可视化的复杂自定义类型的状态。

是的,你可以。一种选择是使用 DebuggerDisplayAttribute

Debugger display attributes allow the developer of the type, who specifies and best understands the runtime behavior of that type, to also specify what that type will look like when it is displayed in a debugger.

[DebuggerDisplay("The count value in my class is: {count}")]
class MyClass
{
   public int count { get; set; }
}

编辑:经过解释我明白了你想要什么。可以自定义 multi-line 可视化工具,但您可能不喜欢这样做的方式:)

  1. 您需要添加对 Microsoft.VisualStudio.DebuggerVisualizers.dll 的引用。我在添加引用 -> 程序集 -> 扩展列表中找到它
  2. 您需要创建新的 class 并继承 DialogDebuggerVisualizer class。覆盖显示方法并显示所需内容。
  3. 将您的 class 标记为 Serializible
  4. 添加对自定义可视化工具的引用

示例代码如下:

using System.Windows.Forms;
using Microsoft.VisualStudio.DebuggerVisualizers;
[assembly: DebuggerVisualizer(typeof(MyClassVisualizer), Target = typeof(MyClass), Description = "My Class Visualizer")]

namespace MyNamespace
{
    [Serializable]
    public class MyClass
    {
        public int count { get; set; } = 5;
    }

    public class MyClassVisualizer : DialogDebuggerVisualizer
    {
        protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
        {
            MyClass myClass = objectProvider.GetObject() as MyClass;

            if (objectProvider.IsObjectReplaceable && myClass != null)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Here is");
                sb.AppendLine("your multi line");
                sb.AppendLine("visualizer");
                sb.AppendLine($"of MyClass with count = {myClass.count}");

                MessageBox.Show(sb.ToString());
            }
        }
    }
}

然后你会看到放大镜,当你点击它时,结果会是这样的:

如果我对你的问题理解正确,那么你可以用 DebuggerTypeProxy 实现你想要的。它会导致调试器在您检查复杂类型的对象时创建并显示代理对象。

在下面的示例中,代理对象包含一个 (multi-line) 字符串 属性,您可以使用文本可视化工具查看它。如果您仍然需要查看底层对象本身,那么这就是 Raw view 按钮的用途。

[DebuggerTypeProxy(typeof(ComplexTypeProxy))]
class ComplexType
{
    // complex state
}

class ComplexTypeProxy
{
    public string Display
    {
        get { return "Create a multi-line representation of _content's complex state here."; }
    }

    private ComplexType _content;

    public ComplexTypeProxy(ComplexType content)
    {
        _content = content;
    }
}