【问题】
在写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 (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# 将对象变量序列化和反序列化为字符串