Pergunta

Java provides java.io.Serializable and java.lang.Cloneable in his standard library (and special support for it in the language and the JVM) for tasks around deserializing/serializing/cloning.

Has C# chosen a different path to provide this functionality, how does the implementation and code using it differ from Java and why was it done this way?

As an example, why does C# use both an attribute (annotation) and an interface for serialization?

Foi útil?

Solução

.NET doesn't use ISerializable as just a marker interface. It acts not only as a marker, but also allows you to control exactly how .NET will serialize the class by implementing GetObjectData and a constructor which takes the suitable arguments.

The attribute is used when the class can be serialized, but you don't want to define your own serialization behavior.

So: Use ISerializable when you want to define your own serialization behavior; or use the [Serializable] attribute when you want to leave it up to the serialization formatter.

Would I call it evolution? I don't know. .NET is just offering you different degrees of flexibility.

Outras dicas

if you want something about serialization: check this

I do not think C# has evolved. Rather, they fixed both things:

  • Serialization in Java is not very clean: deserialization involves object "creation" without calling a constructor, the whole process can include the runtime calling private methods, etc. check the specs if you are curious.

  • Cloneable is just plain broken. It should not be a marker interface, but specify the clone() method. As it is you have Cloneables you cannot clone().

Basically, there are lots of things in Java, mainly from the pre 1.2 days, that are quite broken/messed up/unclean/whatever.

Not sure what you mean by 'evolved', if anything I think the trend is toward attributes rather than marker interfaces. I don't know if Java has gone that way lately as well.

Serialization in the CLR for example is evidenced in its most basic form with attributes, although you can implement a few non-marker interfaces that give you more control over the process if you need it.

Marker interfaces are probably one of the worst decisions ever implemented in Java. I mean just look at how useless Cloneable turned out to be, because nobody defined a public clone() method in the interface.

.NET not going into that direction (at least I'm not aware of any interfaces in that direction) is less of an evolution and more an abandonment of the whole notion. Another direction that seems to be taken more and more seems to be annotations, which I assume you could see as a "marker" but on a more basic level (eg I'm pretty sure if Java was implemented today transient would be an annotation and not a qualifier)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top