如何在 C# 中序列化异常对象? [英] How to serialize an Exception object in C#?

查看:26
本文介绍了如何在 C# 中序列化异常对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 C# 中序列化一个 Exception 对象.但是,这似乎是不可能的,因为 Exception 类未标记为 [可序列化].有没有办法解决这个问题?

I am trying to serialize an Exception object in C#. However, it appears that it is impossible since the Exception class is not marked as [Serializable]. Is there a way to work around that?

如果在应用程序执行过程中出现问题,我想知道发生的异常.

If something goes wrong during the execution of the application, I want to be informed with the exception that occurred.

我的第一反应是序列化它.

My first reflex is to serialize it.

推荐答案

我之前所做的是创建一个自定义的 Error 类.这封装了关于异常的所有相关信息,并且是 XML 可序列化的.

What I've done before is create a custom Error class. This encapsulates all the relevant information about an Exception and is XML serializable.

[Serializable]
public class Error
{
    public DateTime TimeStamp { get; set; }
    public string Message { get; set; }
    public string StackTrace { get; set; }

    public Error()
    {
        this.TimeStamp = DateTime.Now;
    }

    public Error(string Message) : this()
    {
        this.Message = Message;
    }

    public Error(System.Exception ex) : this(ex.Message)
    {
        this.StackTrace = ex.StackTrace;
    }

    public override string ToString()
    {
        return this.Message + this.StackTrace;
    }
}

这篇关于如何在 C# 中序列化异常对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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