Difference between Serializable and MarshalByRefObject

落花浮王杯 提交于 2019-12-09 06:37:01

问题


I am very confused with [Serializable] and :MarshalByRefObject attribute in .NET Remoting .However i read many article on that. If i am using [Serializable] attribute then all methods are executed entirely in callers domain, it means that different callers should have copy of different methods on their own domain and any alteration done by one caller should not reflect on others.But when the same thing i am implementing in my program, i am not getting the desired result.


回答1:


Serializable attribute is used to sign an object that when it is requested through remoting, it will be serialized to a byte array, transferred as byte array from source to destination and then another instance of object is rebuild from that byte array that lives and breathes in destination environment (AppDomain or Application). Manipulations performed on that object is not reflected to the source. To update object you have to make another trip to the source and send your changed object (as a new byte array of course). it is just like downloading a file and modifying it, your changes are not reflected to the server where you have downloaded file from.

var user = server.GetUser("edokan");
user.Alias = "edokan2";

var user2 = server.GetUser("edokan");
//user.Alias == user2.Alias; // is false

On the other hand MarshalByRefObject marks your object that instead of data of your object, a reference to your object is traveled through remoting and every method call/every property manipulation is performed on server side. This is just like posting your question to StackOverflow and reading answers, you have nothing but a browser and a url to view/manipulate question. Everything is performed on StackOverflow servers.

Your confusion arises from a very simple point, MS made remoting sooo simple, one actually thinks that everything is on client side.




回答2:


Adding to @edokan answer, Serializable attribute basically marks a type as being meant to be serialized (i.e, converted to a byte stream).

Frameworks (such as ORM mappers, oodbs, persistence engines) may use this information to take decisions such as whenever the state of objects should be persisted in databases, sent over a network, etc.

You can use classes such BinaryFormatter to take an object marked with the Serializable attribute and create byte stream from it and store it in a file and/or send it over network and latter, reconstruct your object again from these streams.



来源:https://stackoverflow.com/questions/19315786/difference-between-serializable-and-marshalbyrefobject

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