【问题标题】:Can the DebuggerDisplay attribute be applied to types one doesn't own?可以将 DebuggerDisplay 属性应用于不属于自己的类型吗?
【发布时间】:2011-05-27 00:31:53
【问题描述】:

我喜欢DebuggerDisplay 属性。我非常喜欢它,以至于我想在我没有源代码的类型上使用它。

这可能吗?

【问题讨论】:

标签: .net visual-studio debugging


【解决方案1】:

为外部类型 (System.Collections.Generic.KeyValuePair) 设置 DebuggerDisplay 的示例将以下内容添加到 AssemblyInfo.cs:

using System.Collections.Generic;
using System.Diagnostics;

[assembly: DebuggerDisplay("[Key={Key}, Value={Value}]", Target = typeof(KeyValuePair<,>))]

(在VS2015中测试)


2020 年编辑:

无法在 VS2019 中为 KeyValuePair 重现上述内容,但它似乎与 KeyValuePair 有关。

对于非所有类型的私有成员,请尝试这样的操作

类库1:

//using System.Diagnostics;

namespace ClassLibrary1
{
    //[DebuggerDisplay("Foo.Bar={Bar}")] // works too for types you own
    public class Foo
    {
        private int Bar = 42;
    }
}

ConsoleApp1:

using System.Diagnostics;
using System.Reflection;
using ClassLibrary1;

[assembly: DebuggerDisplay("Foo.Bar={FooDebuggerDisplay.Bar(this)}", Target=typeof(Foo))]

class FooDebuggerDisplay
{
    public static int Bar(Foo foo) => (int)foo.GetType().GetField("Bar",BindingFlags.Instance|BindingFlags.NonPublic).GetValue(foo);
}

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var foo = new Foo();
            Debugger.Break();
        }
    }
}

(在 VS2019 中测试)

【讨论】:

  • 我收到错误'Property' is inaccessible due to its protection level 有什么办法解决这个问题吗?这是一个internal
  • @Myster 添加了以非拥有类型显示私有成员的示例
【解决方案2】:

是的。事实上,Microsoft 非常好,将其作为 Visual Studio 的内置选项。

查看“我的文档\Visual Studio 20XX\autoexp.cs”,了解如何将 DebuggerDisplay 属性应用于程序集外的类型的一些示例。然后,添加一些自己的,重新编译并替换 autoexp.dll,然后重新启动 Visual Studio。它应该可以工作。

参考见this MSDN article中黄色的“注”段


或者:我是purchasable extension to Visual Studio 的创建者,它可以轻松地执行此操作,甚至无需停止调试会话。

【讨论】:

  • 不错的答案 - 我尝试了 autoexp 解决方案 - 我想更改调试器显示的第三方代码在实体框架内。 autoexp 的编译失败,因为我没有包含它。如果我可以/我应该在编译中包含其他第三方库,您有什么建议吗?
  • 我找到了,你可以在这里看到完整的说明:tech-archive.net/Archive/VisualStudio/… 它没有任何问题。无需重新启动 Visual Studio。编译 autoexp.dll 后按 F5 就足够了。感谢您的出色回答。
  • 在 VS2015 中仍然可以,但 autoexp.cs 不存在,请参阅:stackoverflow.com/questions/33394892/…
【解决方案3】:

属性是在编译时修饰某些东西(类型、方法、字段等)的一种方式,它们存储在程序集的二进制表示中。在其中添加新属性的一种方法是使用新属性重新编译代码。如果您没有代码,在某些情况下,您可以通过反编译程序集来获取代码。

我能想到的另一种方法,可能是使用反射来加载和处理程序集中的所有类型,然后(通过反射)生成另一个程序集,并将 DebuggerDisplay 添加到您想要的类型(这里是an example

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 2013-06-22
    • 2014-10-14
    • 2010-10-03
    • 2019-07-23
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多