具有属性的自定义例外 [英] Custom exception with properties

查看:45
本文介绍了具有属性的自定义例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过研究,我发现自定义异常应如下所示:

After some research I found that a custom exception should look like this:

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参数的 new 构造函数?

I want above exception to have two additional fields, say int ID and int ErrorCode. How do I add these two fields and initialize them - shall I add a new constructor, with these two parameters and the message parameter?

您还能帮我看看如何为这个具有两个新属性的新类编写序列化方法吗?

Also can you help me and show how to write the serialization methods for this new class which will have the two new properties?

谢谢.

推荐答案

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

It will look something like this. You look for more details here What is the correct way to make a custom .NET Exception serializable?

 [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;
            }
        }

这篇关于具有属性的自定义例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆