[英]Display Properties in Custom Order in Visual Studio Debugger
在 Visual Studio 中,是否可以自定義在調試器中檢查時屬性的顯示順序?
這是一個類的示例,我非常希望 StartDate 和 EndDate 彼此相鄰,即使它們按字母順序分開。
其他調試器選項可通過DebuggerDisplayAttribute
等屬性進行自定義,因此我希望 DisplayOrder 存在另一個此類屬性。
[DebuggerDisplay("{Name}")]
public class Rule
{
public string Name;
public int MaxAge;
public DateTime StartDate;
public DateTime EndDate;
}
在理想的世界中,我希望能夠按照我在類中定義的順序對檢查器中的屬性進行排序(即使這需要在每個屬性上逐步設置調試器順序屬性),因此顯示看起來像這樣:
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; }
}
}
在調試器中看起來像這樣:
反射可能無法保證屬性和字段的順序,但由於視圖僅用於調試目的,所以應該足夠了。 如果沒有,則可以手動構建Properties
數組,限制了可重用性。 在任何一種情況下, Properties
都不是真正的屬性,因此擴展SimpleProperty
數據提示如下所示:
只是為了根據JCL 的建議使用帶有計算屬性的#if DEBUG
。 如果你想在調試器中獲得一些額外的信息,你可以只在調試模式下添加一個字段,如下所示:
[DebuggerDisplay("{Name}")]
public class Rule
{
public string Name;
public int MaxAge;
public DateTime StartDate;
public DateTime EndDate;
#if DEBUG
private string DateRange
{
get { return StartDate.ToString("dd/MM/yyyy") + " - "+
EndDate.ToString("dd/MM/yyyy");
}
}
#endif
}
看起來像這樣:
這會將信息一起呈現,但仍會給檢查員增加噪音。
您可以右鍵單擊變量並“添加監視”並將它們按順序排列在那里。
只是為了讓JCL 建議使用DebuggerTypeProxyAttribute
,您可以添加一個內部類或一個公共類來充當調試視圖的容器
您可以使用數字來強制對調試器視圖類上的屬性進行排序,而無需更改 API 或運行時代碼的性能。
下面是使用 DebuggerTypeProxy 的類的樣子:
[DebuggerDisplay("{Name}")]
[DebuggerTypeProxy(typeof (RuleDebugView))]
public class Rule
{
public string Name;
public int MaxAge;
public DateTime StartDate;
public DateTime EndDate;
internal class RuleDebugView
{
public string _1_Name;
public int _2_MaxAge;
public DateTime _3_StartDate;
public DateTime _4_EndDate;
public RuleDebugView(Rule rule)
{
this._1_Name = rule.Name;
this._2_MaxAge = rule.MaxAge;
this._3_StartDate = rule.StartDate;
this._4_EndDate = rule.EndDate;
}
}
}
在調試器中看起來像這樣:
這不是世界上最干凈的東西,但確實有一點作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.