Serialization Use Cases [closed]

半城伤御伤魂 提交于 2020-01-14 06:04:49

问题


It's not clear to me when should one use serialization / deserialization techniques

Can anybody provide me some basic use case scenarios?


回答1:


Serialization is the process for turning an object into some kind of encoded representation to move it from one place to another. Usually, it's the process of turning an object into something like a byte array or XML string, though you could serialize to other formats if you wanted to.

The most common use of serialization is when you need to move an object across process, machine, or, more precisely, AppDomain boundaries. So if you want to send an object from Server A to Server B, you'd have to serialize the object on Server A, then send that encoded representation of the object to Server B, and have Server B deserialize the object in order to use it on the other end.

Not all objects are easily serializable -- for example, objects which have pointers in memory to some location on a server probably won't make sense if the pointer is sent to another server. In a case like this, you would have to write your own custom logic to determine what to do with that pointer. Perhaps you wouldn't serialize that property of your object at all... Perhaps you'd also serialize what the object that the pointer points to -- it's going to be up to you. That's why serialization isn't always easy or automatic.




回答2:


Couple of obvious examples are when you need to transport an instance of a class across a process boundary (e.g. when using WCF or some other remote communication technology) or you want to persist the instance to a stream (maybe a file).




回答3:


Serialisation is simply the art of representing an instance of an object in a serialized state, allowing them to be recreated into the object type at any time. Two simplistic use cases are simply writing objects to a file and writing them down a Stream (for network communication, or InterProcess Communication, or otherwise).

For example, if you wanted to transfer a simple DTO like so:

public class TestDto
{
    public string TestText { get; set; }
    public string MoreText { get; set; }
}

.. you would to add the [Serializable] and use something such as the BinaryFormatter to be able to read it down the other end of a NetworkStream.

You could not simply write an object instance by default to any form of Stream or file, and have it remain intact at the other side. Of course there are libraries to help with this (such as WCF) which will do the conversion (for [Serializable] classes) internally.

(I'm not sure why you have wpf, but serialization is definitely not specific to WPF)



来源:https://stackoverflow.com/questions/14482832/serialization-use-cases

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!