C# &引用;反映类型“”时出错;在C中#

C# &引用;反映类型“”时出错;在C中#,c#,.net,exception,serialization,C#,.net,Exception,Serialization,我需要序列化和异常,我创建了一个可序列化的类 [Serializable] public class MessageException : Exception { public string Exception { get; set; } public MessageException() { } public MessageException(System.Exception ex) { this.Exception = ex.

我需要序列化和异常,我创建了一个可序列化的类

[Serializable]
public class MessageException : Exception
{
    public string Exception
    { get; set; }
    public MessageException()
    { }
    public MessageException(System.Exception ex) 
    {
        this.Exception = ex.Message.ToString();
    }
}
当出现以下异常时,我尝试从中调用该类

catch (Exception ex)
        {
            MessageException exception = new MessageException(ex);
            var exSerializer = new XmlSerializer(typeof(MessageException));


            var writer = new StringWriter();
            exSerializer.Serialize(writer, exception);
            writer.Close();
            Compair2Files(writer.ToString(), BaseString);
        }
它在第二行“var exSerializer=new XmlSerializer(typeof(MessageException));”失败

我实际上想做的是,当我捕获异常时,我想序列化它,然后将它存储到我的单元测试程序的文件中。 你能帮我吗 提前谢谢
Jp

不能使用
XmlSerializer
序列化异常
您需要使用二进制序列化

基本的
异常
类已经是
[Serializale]
,因此您的类是无用的。

这也是错误的;您正在忽略堆栈跟踪。

确定的可能重复现在我的问题如果我使用需要使用流的二进制文件,可以将流存储到字符串而不是文件中吗??mean Stream=(此处允许我将其存储到字符串中的内容)是否可以使用Memorystream?否。无法将异常序列化为字符串。相反,您可以只调用
ex.ToString()
,它将返回相关信息。您可以使用
MemoryStream
将二进制数据存储在内存中。下面是我的代码:现在捕获(异常ex){MemoryStream mStream=new MemoryStream();binarySformatter bFormatter=new binarySformatter();bFormatter.Serialize(mStream,ex);Compair2Files(mStream.ToString(),BaseString);}出现错误,表示序列化异常未处理,任何标识符,
mStream.ToString()
都没有意义。无法获取人类可读的字符串。