Why does Binary Serialization require the object to be marked as serializable?
I was using the xml serializer but when I switched to binary serialization, it throws an exception:
Runtime error: dotNet runtime exception: 开发者_开发问答Type 'MyTypes.MyObject' in Assembly 'MyTypes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
Why is it different than an xml serializer in the way it asks this?
Just marking the object as serializable is enough to solve this? I don't want to specify how the serialization should occur.
XmlSerializer
is safe to use in all cases because it only serializes publicly accessible data, that users of the class could access anyway.
Any of the runtime formatters (including BinaryFormatter
) serialize both publicly and privately accessible information, so may give callers access to information that they otherwise shouldn't have. By marking your type as [Serializable]
you're effectively saying that you've thought about this and are granting permission to anybody to look at the serialized information about your type.
This is a "safe by default" choice so that you don't accidentally end up serializing sensitive data like credit card details or whatever into places they shouldn't be such as logs or databases.
The fundamental difference between the BinaryFormatter and xml serializers (other than the obvious output format) is that binary serialization preserves type information (private/public properties, methods, events, etc...). That's one of the reason this type of serialization is used with remoting. The only requirement is to decorate the type with the SerializableAttribute.
精彩评论