LdapException序列化问题 - ErrorCode变为零 - .NET错误,还是打算?

时间:2011-04-15 19:47:11

标签: c# .net serialization

我发现当我序列化和反序列化System.DirectoryServices.Protocols.LdapException class ErrorCode属性没有被序列化时。我的测试代码如下:

using System;
using System.DirectoryServices.Protocols;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace TestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            LdapException origExcept = new LdapException(81, "Error code of 81 was set originally.");

            Console.WriteLine("LdapException error code is: " + origExcept.ErrorCode);
            Console.WriteLine("LdapException message code is: " + origExcept.Message);

            // Try independant deep clone
            LdapException ldapClone = (LdapException)deepCloneSerialize(origExcept);
            Console.WriteLine("deep clone error code is: " + ldapClone.ErrorCode);
            Console.WriteLine("deep clone message code is: " + ldapClone.Message);

            // Try binary deep clone
            LdapException binaryClone = (LdapException)binaryCloneSerialize(origExcept);
            Console.WriteLine("binary clone error code is: " + binaryClone.ErrorCode);
            Console.WriteLine("binary clone message code is: " + binaryClone.Message);
        }


        private static object deepCloneSerialize(object obj)
        {
            MemoryStream ms = new MemoryStream();

            DataContractSerializer testSer = new DataContractSerializer(obj.GetType());
            testSer.WriteObject(ms, obj);

            // Now de-serialize and return it
            ms.Seek(0, SeekOrigin.Begin);
            return testSer.ReadObject(ms);

        }

        private static object binaryCloneSerialize(object obj)
        {
            MemoryStream ms = new MemoryStream();

            BinaryFormatter myBinFormat = new BinaryFormatter();
            myBinFormat.Serialize(ms, obj);

            // Now de-serialize and return it
            ms.Seek(0, SeekOrigin.Begin);
            return myBinFormat.Deserialize(ms);
        }
    }
}

该程序的输出如下:

LdapException error code is: 81
LdapException message code is: Error code of 81 was set originally.
deep clone error code is: 0
deep clone message code is: Error code of 81 was set originally.
binary clone error code is: 0
binary clone message code is: Error code of 81 was set originally.

我已经在3.5和4.0 .NET版本的VS 2008和VS 2010中尝试了这个,上面有两种序列化机制,两者都有相同的结果。奇怪的是,某些方面可以通过OK,例如异常消息本身,但其他部分则没有。

所以,我不应该序列化异常(为什么它们标有Serializable属性呢?)这是一个症状,或者这是.NET框架中的一个错误?

0 个答案:

没有答案