带有属性的自定义异常
本文关键字:自定义异常 属性 | 更新日期: 2023-09-27 18:16:49
经过一番研究,我发现一个自定义异常应该是这样的:
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) { }
}
}
但是我有一个小问题。
我希望上面的异常有两个额外的字段,比如int ID
和int ErrorCode
。我如何添加这两个字段并初始化它们——我是否应该添加一个新的构造函数,带有这两个参数和message参数?
你也可以帮助我,并展示如何编写序列化方法这个新的类,将有两个新的属性?
谢谢。
看起来像这样。什么是使自定义。net异常可序列化的正确方法?
[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;
}
}