C#调试:[DebuggerDisplay]或ToString()?(C# debugging: [DebuggerDisplay] or ToString()?)

编程入门 行业动态 更新时间:2024-10-26 05:23:06
C#调试:[DebuggerDisplay]或ToString()?(C# debugging: [DebuggerDisplay] or ToString()?)

有两种方法可以增加调试信息的有用性,因此您在调试器中看不到{MyNamespace.MyProject.MyClass} 。 这些是使用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); } }

有没有理由选择一个对另一个? 任何理由不做这两个 纯粹是个人喜好吗?

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

These are the use of the [DebuggerDisplayAttribute][1] and the ToString() method.

using System.Diagnostics; ... [DebuggerDisplay("Name = {Name}")] public class Person { public string Name; }

or

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()具有在运行时更改显示的“副作用”。

这可能是或可能不是一件好事。

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

例如,在你的情况下,“ToString”实现对我来说似乎是奇怪的。 我会期望一个“Person”类ToString()实现只是直接返回名称,而不是“Name = PersonsName”。 但是,在调试期间,我可能需要额外的信息。

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

This may or may not be a good thing.

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

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.

更多推荐

本文发布于:2023-08-01 08:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1356730.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DebuggerDisplay   ToString   debugging

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!