为什么 .NET 异常是可变的?

发布于 2024-09-06 08:04:27 字数 302 浏览 10 评论 0原文

我想知道为什么基类库中的 .NET 异常类默认有一些可变成员

  • 为什么我可以更改 SourceHelpLinkData 中的值code>,但无法更改诸如 Message 之类的其他内容?
  • 为什么抛出异常会重写 StackTrace 使其变得可变?将堆栈跟踪信息附加到现有跟踪是否是更好的设计(但仍然可变)?
  • .NET 异常设计可能有哪些改进?

我只是对设计选择感兴趣......

I'm wondering why .NET exceptions classes from Base Class Library has some mutable members by default

  • Why I can change the Source, HelpLink and values from Data, but can't change anything else like the Message?
  • Why throwing the exception rewrites the StackTrace making it mutable too? Is appending the stack trace information to existing trace would be better design (but still mutable)?
  • What possible improvements in .NET exceptions design may be?

I'm interesting just in design choices...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

新雨望断虹 2024-09-13 08:04:27

StackTrace 至少对我来说是有意义的。这个想法是,Exception(作为对象)可以被传递、从方法返回等。StackTrace 仅在抛出和捕获异常时才重要。从某种意义上说,StackTrace 实际上更多的是异常抛出的属性,而不是 Exception 对象本身。

关于其他属性的可变性,我认为这只是因为通过分配属性来构造实例比将它们全部强制放入构造函数更容易。请记住,在设计 Exception 时,C# 没有可选参数。

您可以考虑重新设计,其中 Exception 和派生类是不可变的,但这需要异常工厂或构建器类。它只会使从 Exception 派生变得更加复杂。

The StackTrace makes sense to me, at least. The idea is that an Exception (as an object) may be passed around, returned from methods, etc. The StackTrace is only important as an exception is thrown and caught. In a sense, StackTrace is really more of a property of the throwing of the exception, not the Exception object itself.

Regarding the mutability of the other properties, I assume it is just because it's easier to construct an instance by assigning to properties rather than forcing them all into the constructor. Remember that at the time Exception was designed, C# did not have optional parameters.

You could consider a re-design where Exception and derived classes are immutable, but this would require an exception factory or builder class. It would just make deriving from Exception that much more complex.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文