带属性的自定义exception

经过一些研究后,我发现自定义exception应如下所示:

using System; using System.Runtime.Serialization; namespace YourNamespaceHere { [Serializable()] public class YourCustomException : Exception, ISerializable { public YourCustomException() : base() { } public YourCustomException(string message) : base(message) { } public YourCustomException(string message, System.Exception inner) : base(message, inner) { } public YourCustomException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } 

但我有小问题。

我希望上面的exception有两个额外的字段,比如int IDint ErrorCode 。 如何添加这两个字段并初始化它们 – 我应该添加一个新的构造函数,这两个参数和消息参数?

你也可以帮助我并展示如何为这个具有两个新属性的新类编写序列化方法吗?

谢谢。

它看起来像这样。 您在此处查找更多详细信息使自定义.NETexception可序列化的正确方法是什么?

  [Serializable()] public class YourCustomException : Exception, ISerializable { public Int Id { get; set; } public Int ErrorCode { get; set; } public YourCustomException() : base() { } public YourCustomException(string message) : base(message) { } public YourCustomException(string message, System.Exception inner) : base(message, inner) { } public YourCustomException(SerializationInfo info, StreamingContext context) : base(info, context) { } public YourCustomException(string message, int Id, int ErrorCode) : base(message) { this.Id = Id; this.ErrorCode = ErrorCode; } }