C# Serialize() 抛出System.Runtime.Serialization.SerializationException

来源:互联网 发布:ebsco外文期刊数据库 编辑:程序博客网 时间:2024/06/15 11:03

因为要往socket发送数据,需要把instance序列化(Serialization),用下面的函数发现会抛出SerializationException,Exception thrown: 'System.Runtime.Serialization.SerializationException' in mscorlib.dll.

        ///<summary>         /// 序列化         /// </summary>         /// <param name="data">要序列化的对象</param>         /// <returns>返回存放序列化后的数据缓冲区</returns>         public static byte[] Serialize(object data)        {            BinaryFormatter formatter = new BinaryFormatter();            MemoryStream mems = new MemoryStream();            formatter.Serialize(mems, data);            return mems.GetBuffer();        }

class定义与序列化调用代码如下:

        class FeedbackObj        {            public FeedbackObj() { }            public string mUserName;            public int mUserId;            public string mContent;            public string mEmail;        }  
        byte[] buff = new byte[1024];        FeedbackObj fb = new FeedbackObj();        fb.mUserId = 1234;        fb.mUserName = "YOUQ";        fb.mContent = sendMessage;        fb.mEmail = "Youqi.Cai@xxx.com";        buff = Serialize(fb); 



查阅MSDN发现原来是需要序列化的class的定义需要mark it with the Serializable attribute。

[Serializable]public class MyObject {  public int n1 = 0;  public int n2 = 0;  public String str = null;}


附上MSDN关于序列化的几点建议大致意思:

确定一个class是否要定义为serializable 应该思考几个问题:该类是否有夸应用程序使用的需求?是否可能被远程使用(通过socket发送? By Youqi.)?该类的派生类是否有可能需要被序列化呢?等等。如果不确定就建议用serializable修饰,除非有以下下情况:

2.如果包含只有在当前这一个实例中有效的特殊的成员(unmanaged memory or file handles),可用NonSerialized 修饰,实例化过程中将忽略该元素;

3.如果类中数据成员包含敏感信息,需要有选择性的对成员进行序列化,建议implement ISerializable 来实现,做法更灵活。


原文如下:

Serialization Guidelines

You should consider serialization when designing new classes since a class cannot be made serializable after it has been compiled. Some questions to ask are: Do I have to send this class across application domains? Will this class ever be used with remoting? What will my users do with this class? Maybe they derive a new class from mine that needs to be serialized. When in doubt, mark the class as serializable. It is probably better to mark all classes as serializable unless:

  • They will never cross an application domain. If serialization is not required and the class needs to cross an application domain, derive the class from MarshalByRefObject.
  • The class stores special pointers that are only applicable to the current instance of the class. If a class contains unmanaged memory or file handles, for example, ensure these fields are marked as NonSerialized or don't serialize the class at all.
  • Some of the data members contain sensitive information. In this case, it will probably be advisable to implement ISerializable and serialize only the required fields.

0 0