【问题标题】:Custom exception with properties具有属性的自定义异常
【发布时间】:2016-01-07 00:06:51
【问题描述】:

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

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 IDint ErrorCode。如何添加这两个字段并初始化它们 - 我应该添加一个 new 构造函数,带有这两个参数和消息参数吗?

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

谢谢。

【问题讨论】:

  • 只需将属性添加到您的类中
  • @singsuyash:我应该添加接受消息和两个整数的 new 构造函数吗?如果有人能用这两个整数属性总结这些事情以及你链接的内容作为我班级的答案,那就太好了。
  • Shetty 为你添加了一个例子

标签: c# .net


【解决方案1】:

它看起来像这样。 您可以在这里查看更多详细信息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;
            }
        }

【讨论】:

  • 我可以在我的异常类中添加一些自定义方法吗?
  • 捕获自定义异常后,您可以调用这些方法。我想知道用这种方法会做什么。如果该方法抛出异常,您是否准备好接收未处理的异常或跳转到另一个捕获。
  • @singsuyash: 该方法可能只会初始化一些将传递给该方法的类对象的成员变量
  • @singsuyash 我们可以将其实现为属性吗?
  • @Zaker,对不起,我失去了关于这个的上下文,我过几天再回来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-14
  • 2011-11-28
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
相关资源
最近更新 更多