gpt4 book ai didi

c# - 在 Visual Studio 调试器中以自定义顺序显示属性

转载 作者:太空狗 更新时间:2023-10-30 01:18:11 25 4
gpt4 key购买 nike

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

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

example

其他调试器选项可通过 DebuggerDisplayAttribute 等属性自定义,所以我希望 DisplayOrder 存在另一个这样的属性。

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

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

ideal debugger

最佳答案

Pinnable Properties在 VS2019+ 中是目前的一种方法,因为您可以使用 pin 按正确顺序固定您的属性数据提示内的按钮。

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

进一步扩展KyleMit's answer ,并使用反射加载成员和字段列表,使这样的调试 View 可重用:

[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; }
}
}

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

datatip with ordered 'properties'

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

expanded datatip showing PropertyName and Value properties of SimpleProperty

注意属性(property)督察magnifyng glass只能在扩展的 SimpleProperty.Value 中使用,这可能会带来不便。

关于c# - 在 Visual Studio 调试器中以自定义顺序显示属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28504884/

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