My task was to serialize and deserialize an object.
I want to know:
Instead of passing the object in the Serialize Method, I am passing object.properties
. Does this affect it in any way?
FileStream fs = new FileStream(@"D:\Rough Work\Serialization\Serialization\bin\Debug\Log.txt",FileMode.OpenOrCreate);
Laptop obj = new Laptop();
obj.Model = 2;
obj.SerialNumber = 4;
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, obj.Model);
formatter.Serialize(fs, obj.SerialNumber);
[Serializable]
class Laptop
{
public int Model;
public int SerialNumber;
}
You don't need to serialize the properties individually. You can just serialize the entire object and deserialize it the same way.
using (var fs = new FileStream(@"D:\\Rough Work\\Serialization\\Serialization\\bin\\Debug\\Log.txt",FileMode.OpenOrCreate)) { var formatter = new BinaryFormatter(); formatter.Serialize(fs, obj); } using (var fs = new FileStream(@"D:\\Rough Work\\Serialization\\Serialization\\bin\\Debug\\Log.txt",FileMode.OpenOrCreate)) { var formatter = new BinaryFormatter(); obj = formatter.Deserialize(fs) as Laptop; }
If your question is how would Laptop class know that it is being serialized then you might want to implement ISerializable interface.
您可以将序列化的方法转换为字符串,并将其输出到调试窗口
I want to know: Whether my object is serialized in the way I'm doing it
Then you can use xml serialization, that way you can check your serialized object since it will be in human-readable form.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.