c# – 带属性的自定义异常

c# – 带属性的自定义异常,第1张

概述经过一些研究后,我发现自定义异常应如下所示: using System;using System.Runtime.Serialization;namespace YourNamespaceHere{ [Serializable()] public class YourCustomException : Exception, ISerializable { 经过一些研究后,我发现自定义异常应如下所示:
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.如何添加这两个字段并初始化它们 – 我应该添加一个新的构造函数,这两个参数和消息参数?

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

谢谢.

解决方法 它看起来像这样.
你在这里寻找更多细节 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,inner) { }            public YourCustomException(SerializationInfo info,context) { }            public YourCustomException(string message,int ID,int ErrorCode)                : base(message)            {                this.ID = ID;                this.ErrorCode = ErrorCode;            }        }
总结

以上是内存溢出为你收集整理的c# – 带属性的自定义异常全部内容,希望文章能够帮你解决c# – 带属性的自定义异常所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1250030.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存