C# 具有属性的自定义异常
经过一些研究,我发现自定义异常应该如下所示:C# 具有属性的自定义异常,c#,.net,C#,.net,经过一些研究,我发现自定义异常应该如下所示: using System; using System.Runtime.Serialization; namespace YourNamespaceHere { [Serializable()] public class YourCustomException : Exception, ISerializable { public YourCustomException() : base() { }
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
。如何添加这两个字段并对其进行初始化?是否要添加一个新的构造函数,并使用这两个参数和消息参数
您还可以帮助我并演示如何为这个将具有两个新属性的新类编写序列化方法吗
谢谢。它看起来像这样。 您可以在此处查看更多详细信息
只需将属性添加到您的类中就可以找到@singsuyash:我要添加一个新的构造函数来获取消息和两个整数吗?如果有人能总结这些东西,以及你用这两个整数属性为我的类链接的答案,那就太好了。Shetty为你添加了一个例子。我能不能也给我的异常类添加一些自定义方法?捕获自定义异常后,你可以调用这些方法。我想知道我们将用这种方法做什么。您准备好接收未处理的异常了吗?或者,如果该方法引发异常,您准备好跳转到另一个catch。@singsuyash:该方法可能只初始化将传递给该类的某个类对象的成员变量method@singsuyash我们可以把它作为一个属性来实现吗。@扎克,很抱歉,我丢失了这个属性的上下文,我几天后回来。
[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;
}
}