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

在尝试使用C#的Serialize()方法将实例数据发送到socket时遇到了System.Runtime.Serialization.SerializationException异常。异常发生在mscorlib.dll中。问题可能源于类不支持跨应用程序域序列化、包含特定于实例的指针或者数据成员包含敏感信息。解决办法包括避免跨应用域序列化、标记不安全字段为NonSerialized或仅序列化必要字段。
部署运行你感兴趣的模型镜像

因为要往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.

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

C#中,`System.Runtime.Serialization.Formatters.Binary.BinaryFormatter` 类主要用于对象的序列化和反序列化操作。 序列化是将对象转换为字节流的过程,这样对象的数据就可以被存储到文件、数据库或者通过网络进行传输。反序列化则是将字节流转换回对象的过程 [^1]。 `BinaryFormatter` 以缩略型二进制格式将对象数据写到一个文件中,速度比较快,而且写入后的文件以二进制保存,有一定的保密效果 [^2]。 使用 `BinaryFormatter` 进行序列化和反序列化的具体方法如下: - **序列化**:使用 `BinaryFormatter.Serialize(Stream, object)` 方法,将需要转换的对象和 `Stream` 引用传入,就会得到包含对象数据的 `stream` 对象 [^1]。 - **反序列化**:使用 `BinaryFormatter.Deserialize(Stream stream)` 方法,传入 `stream` 引用,该方法会返回反序列化后的对象 [^1]。 以下是一个简单的示例代码: ```csharp using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace Client.Chapter_11___File_and_Streams { class Class1 { [STAThread] static void Main(string[] args) { Point p1 = new Point(); p1.xpoint = 0x1111; p1.ypoint = 0x2222; // 序列化操作 Stream stream = File.Open("onepoint.bin", FileMode.Create); BinaryFormatter bformatter = new BinaryFormatter(); bformatter.Serialize(stream, p1); stream.Close(); // 反序列化操作 Stream openStream = File.Open("onepoint.bin", FileMode.Open); Point deserializedPoint = (Point)bformatter.Deserialize(openStream); } } [Serializable()] class Point { public int xpoint; public int ypoint; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值