DebuggerDisplay 属性可以应用于 Microsoft.Office.Interop.Word.Range 吗?
Can the DebuggerDisplay attribute be applied to Microsoft.Office.Interop.Word.Range?
根据这个问题 Can the DebuggerDisplay attribute be applied to types one doesn't own 的提问,是否可以将 DebuggerDisplay
属性应用于外部程序集的类型?
如果是这样,有没有办法将它专门应用于 Microsoft.Office.Interop.Word.Range
?
我尝试了以下代码,但没有成功:
<Assembly: DebuggerDisplay("text: {Text}", Target:=GetType(Word.Range))>
在运行时调试器显示这个字符串:
{System.__ComObject}
但是 'System.__ComObject' 无法访问,因为它是 'Friend'。
But 'System.__ComObject' is not accessible because it is 'Friend'.
没错。但是 System.__ComObject
继承自 public MarshalByRefObject
。 DebuggerDisplay
属性将适用于所有派生的 classes,如果您将其设置为它们的基础 class。因此,您可以将 typeof(MarshalByRefObject)
设置为 DebuggerDisplay
属性的目标。
如果你这样做,你不能只在格式化程序中使用 {Text}
,因为 MarshalByRefObject
没有这样的 属性。为了克服这个问题,您可以定义简单的静态助手来检查传递的对象的类型。如果它是 Range
,它将调用 Text
。否则它将默认为 obj.ToString()
:
public static class DisplayHelper
{
public static string DisplayRange(MarshalByRefObject obj)
{
var range = obj as Range;
return range?.Text ?? obj?.ToString() ?? "The value is null";
}
}
现在您可以设置 DebuggerDisplay
属性:
[assembly: DebuggerDisplay("text: {FullNamespace.Here.DisplayHelper.DisplayRange(this)}"
, Target = typeof(MarshalByRefObject))]
请务必为 DisplayHelper
class 指定完整的命名空间(将 FullNamespace.Goes.Here
替换为您的实际命名空间)。
这是调试器中的结果视图:
根据这个问题 Can the DebuggerDisplay attribute be applied to types one doesn't own 的提问,是否可以将 DebuggerDisplay
属性应用于外部程序集的类型?
如果是这样,有没有办法将它专门应用于 Microsoft.Office.Interop.Word.Range
?
我尝试了以下代码,但没有成功:
<Assembly: DebuggerDisplay("text: {Text}", Target:=GetType(Word.Range))>
在运行时调试器显示这个字符串:
{System.__ComObject}
但是 'System.__ComObject' 无法访问,因为它是 'Friend'。
But 'System.__ComObject' is not accessible because it is 'Friend'.
没错。但是 System.__ComObject
继承自 public MarshalByRefObject
。 DebuggerDisplay
属性将适用于所有派生的 classes,如果您将其设置为它们的基础 class。因此,您可以将 typeof(MarshalByRefObject)
设置为 DebuggerDisplay
属性的目标。
如果你这样做,你不能只在格式化程序中使用 {Text}
,因为 MarshalByRefObject
没有这样的 属性。为了克服这个问题,您可以定义简单的静态助手来检查传递的对象的类型。如果它是 Range
,它将调用 Text
。否则它将默认为 obj.ToString()
:
public static class DisplayHelper
{
public static string DisplayRange(MarshalByRefObject obj)
{
var range = obj as Range;
return range?.Text ?? obj?.ToString() ?? "The value is null";
}
}
现在您可以设置 DebuggerDisplay
属性:
[assembly: DebuggerDisplay("text: {FullNamespace.Here.DisplayHelper.DisplayRange(this)}"
, Target = typeof(MarshalByRefObject))]
请务必为 DisplayHelper
class 指定完整的命名空间(将 FullNamespace.Goes.Here
替换为您的实际命名空间)。
这是调试器中的结果视图: