最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】C# 将对象变量序列化和反序列化为字符串

C# crifan 4704浏览 0评论

【问题】

在写C#代码的时候,需要将某个CookieCollection的变量,序列化为一个字符串,保存起来。

之后再将保存的字符串反序列化为CookieCollection,继续使用。

对于序列化和反序列化,是通过之前Python中的序列化(pickling )而想到的。

【解决过程】

1.网上找的很多资料,都只是将某个对象序列化后,存为某个文件的,比如:
深入C# 序列化(Serialize)、反序列化(Deserialize)
但是我这里需要的是,将对象序列化为字符串,以方便保存在别处,而不是文件。

2.最后是参考这里:

serialize/deserialize object into string
而实现了将一个对象(CookieCollection)序列化为字符串的,
然后自己照葫芦画瓢去实现了对应的反序列化该字符串位原先的CookieCollection对象。
代码如下:

MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, skydriveCookies); //skydriveCookies is CookieCollection
string CookiesStr = System.Convert.ToBase64String(memoryStream.ToArray());

CookieCollection restoredCookies = new CookieCollection();
byte[] cookiesBytes = System.Convert.FromBase64String(CookiesStr);
MemoryStream restoredMemoryStream = new MemoryStream(cookiesBytes);
restoredCookies = (CookieCollection)binaryFormatter.Deserialize(restoredMemoryStream);

【关于C#(.NET)中的序列化】

相关资料,引用

Serialization in C#

的解释:

Serialization (known as pickling in python) is an easy way to convert an object to a binary representation that can then be e.g. written to disk or sent over a wire.

It’s useful e.g. for easy saving of settings to a file.

You can serialize your own classes if you mark them with [Serializable] attribute. This serializes all members of a class, except those marked as [NonSerialized].

.NET offers 2 serializers: binary, SOAP, XML. The difference between binary and SOAP is:

  • binary is more efficient (time and memory used)
  • binary is not human-readable. SOAP isn’t much better.

XML is slightly different:

  • it lives in System.Xml.Serialization
  • it uses [XmlIgnore] instead of [NonSerialized] and ignores [Serializable]
  • it doesn’t serialize private class members

【后记】

后来打算把上面的那个CookieCollection,和别的几个字符串变量,合并成为一个struct变量,然后把struct变量传入序列化函数,结果:

binaryFormatter.Serialize(memoryStream, obj);

会异常而死掉,结果证实了,Serialize只能针对已经存在的类型的object对象,而对于自己创建的struct结构体变量,是不支持的。

转载请注明:在路上 » 【已解决】C# 将对象变量序列化和反序列化为字符串

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (1)

  1. 非常感觉您的文章,正好是我需要的。我本打算用sqlite的blob字段存储序列化后的byte[],但是在反序列的时候问题不对,一直找不到原因,最后无奈,还是用您的方法,存为string,到哪都通过,太方便了。再次感谢 。 顺便说一下,对于自定义的class(我是新手,不知道class是否是您说的struct),只要在上面加上[Serializable]就可以序列化了(没亲自测试,不清楚)
    kom12年前 (2012-09-21)回复
85 queries in 0.174 seconds, using 22.08MB memory