为什么 .NET 异常是可变的?
我想知道为什么基类库中的 .NET 异常类默认有一些可变成员
- 为什么我可以更改
Source
、HelpLink
和Data
中的值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 fromData
, but can't change anything else like theMessage
? - 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
StackTrace 至少对我来说是有意义的。这个想法是,
Exception
(作为对象)可以被传递、从方法返回等。StackTrace
仅在抛出和捕获异常时才重要。从某种意义上说,StackTrace 实际上更多的是异常抛出的属性,而不是 Exception 对象本身。关于其他属性的可变性,我认为这只是因为通过分配属性来构造实例比将它们全部强制放入构造函数更容易。请记住,在设计
Exception
时,C# 没有可选参数。您可以考虑重新设计,其中 Exception 和派生类是不可变的,但这需要异常工厂或构建器类。它只会使从 Exception 派生变得更加复杂。
The
StackTrace
makes sense to me, at least. The idea is that anException
(as an object) may be passed around, returned from methods, etc. TheStackTrace
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 theException
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 fromException
that much more complex.