在 VS 中检查时,有什么方法可以使对象的属性以特定顺序出现?

Any way to make properties of an object to appear in a particular order when inspecting in VS?

我有一个遗留项目,我经常可以在其中看到具有多达 100 个属性的模型 类,并且在调试时我希望以特定顺序查看它们,因为它是一个有序的数据序列。是否有任何类型的属性可以使 Visual Studio 调试器以特定顺序显示它们而不是按名称排序?

您可以使用 DebuggerDisplayAttribute class 自定义调试器描述。请阅读MSDN

如果将该属性附加到某些 class,您可以定义在调试期间如何查看描述。

来自 MSDN 的一个示例。这里 valuekey 在调试期间会更明显:

[DebuggerDisplay("{value}", Name = "{key}")]
internal class KeyValuePairs
{
    private IDictionary dictionary;
    private object key;
    private object value;

    public KeyValuePairs(IDictionary dictionary, object key, object value)
    {
        this.value = value;
        this.key = key;
        this.dictionary = dictionary;
    }
}

这里调试时更容易看到值和键。

您可以考虑 DebuggerBrowsableAttribute 来确定调试器将显示某些成员的内容。您甚至可以隐藏一些成员。

这里是 DebuggerBrowsableAttribute 的一些例子:

public class User
{
    [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
    public string Login { get; set; }

    [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
    public FullName Name { get; set; }

    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    public string HashedPassword { get; set; }
}

如您所见属性 HashedPassword 将从调试中隐藏。

此外,您可以在 Visual Studio 中使用 Watch window 并配置您要跟踪的变量。

您可以使用 DebuggerDisplay 属性来控制调试时数据在工具提示中的显示方式,例如

[DebuggerDisplay("Age = {Age}, Name = '{Name}'")]
public class Person
{
    public string Name { get; set; }

    public int Age { get; set; }
}

供参考: