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

C# 同时被 3 个专栏收录
3 篇文章 0 订阅
3 篇文章 0 订阅
1 篇文章 0 订阅

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

        /// 序列化 
        /// </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 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。

public class MyObject {
  public int n1 = 0;
  public int n2 = 0;
  public String str = null;


确定一个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.

  • 1
  • 0
  • 0
  • 一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
钱包余额 0