C#调试:[DebuggerDisplay]还是ToString()? [英] C# debugging: [DebuggerDisplay] or ToString()?

查看:112
本文介绍了C#调试:[DebuggerDisplay]还是ToString()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种方法可以提高调试信息的实用性,而不是在调试器中看到 {MyNamespace.MyProject.MyClass}

There are two ways to increase the usefulness of debugging information instead of seeing {MyNamespace.MyProject.MyClass} in the debugger.

这些是 DebuggerDisplayAttribute ToString()方法。

using System.Diagnostics;
...

[DebuggerDisplay("Name = {Name}")]
public class Person
{
    public string Name;
}

public class Person
{
    public string Name;
    public override string ToString()
    {
        return string.Format("Name = {0}", Name);
    }
}

有没有理由偏爱一个?有什么理由不做这两件事?纯粹是个人喜好吗?

Is there any reason to prefer one to the other? Any reason not to do both? Is it purely personal preference?

推荐答案

使用 [DebuggerDisplay] 是指仅适用于调试器。覆盖ToString()具有在运行时更改显示的副作用。

Using [DebuggerDisplay] is meant only for the debugger. Overriding ToString() has the "side effect" of changing the display at runtime.

这可能不是好事。

通常,您在调试过程中需要比标准 ToString()输出更多的信息,在这种情况下,同时使用。

Often, you want more info during debugging than your standard ToString() output, in which case you'd use both.

例如,在您的情况下, ToString实现对我来说似乎很奇怪。我希望 Person类的ToString()实现仅直接返回Name,而不是 Name = PersonsName。但是,在调试期间,我可能需要这些额外的信息。

For example, in your case, the "ToString" implementation seems odd to me. I would expect a "Person" class ToString() implementation to just return the Name directly, not "Name = PersonsName". However, during debugging, I might want that extra information.

这篇关于C#调试:[DebuggerDisplay]还是ToString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆