在 Visual Studio 调试器中按自定义顺序显示属性

Kyl*_*Mit 8 .net c# debugging visual-studio-2010 visual-studio

在 Visual Studio 中,是否可以自定义在调试器中检查时属性的显示顺序?

这是一个类的示例,我非常希望 StartDate 和 EndDate 彼此相邻,即使它们按字母顺序分开。

例子

其他调试器选项可通过像 的属性进行自定义DebuggerDisplayAttribute,因此我希望 DisplayOrder 会存在另一个这样的属性。

[DebuggerDisplay("{Name}")]
public class Rule
{
    public string Name;
    public int MaxAge;
    public DateTime StartDate;
    public DateTime EndDate;
}
Run Code Online (Sandbox Code Playgroud)

理想的世界中,我希望能够按照我在类中定义的顺序对检查器中的属性进行排序(即使这需要在每个属性上逐步设置调试器顺序属性),因此显示看起来像这样:

理想的调试器

小智 8

VS2019+ 中的可固定属性是当前的一种方法,因为您可以使用别针数据提示内的按钮。

然而,在更通用、可重用的方法中,该[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]属性可以用在有序属性名称和值对的数组上。这使得调试视图能够“展平”数组根,以正确的顺序列出属性。

进一步扩展KyleMit 的答案,并使用反射加载成员和字段列表,使得这样的调试视图可重用:

[DebuggerDisplay("{Name}")]
[DebuggerTypeProxy(typeof(OrderedPropertiesView))]
public class Rule
{
    public string Name;
    public int MaxAge;
    public DateTime StartDate;
    public DateTime EndDate;        
}

public class OrderedPropertiesView
{
    [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
    public SimpleProperty[] Properties { get; }

    public OrderedPropertiesView(object input)
    {
        this.Properties = input.GetType()
            .GetFields(BindingFlags.Public | BindingFlags.Instance)
            .Select(prop => new SimpleProperty(prop, input))
            .ToArray();
    }

    [DebuggerDisplay("{Value}", Name = "{PropertyName,nq}")]
    public class SimpleProperty
    {
        public SimpleProperty(MemberInfo member, object input)
        {
            this.Value = GetValue(member, input);
            this.PropertyName = member.Name;
        }

        private object GetValue(MemberInfo member, object input)
        {
            switch (member)
            {
                case FieldInfo fi: return fi.GetValue(input);
                case PropertyInfo pi: return pi.GetValue(input);
                default: return null;
            }
        }

        public object Value { get; internal set; }
        public string PropertyName { get; internal set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

在调试器中看起来像这样:

带有有序“属性”的数据提示

反射可能无法保证属性和字段的顺序,但由于视图仅用于调试目的,因此应该足够了。如果没有,则Properties可以手动构建数组,从而限制了可重用性。在任何一种情况下,Properties都不是真正的属性,因此扩展SimpleProperty数据提示如下所示:

显示 SimpleProperty 的 PropertyName 和 Value 属性的扩展数据提示

请注意,物业检查员放大镜只能在扩展中使用SimpleProperty.Value,这可能会带来不便。