Is it possible to deserialize (c#) a piece o开发者_如何转开发f xml, csv, json (whatever it is), and not know it's type? But be given back an object (which ultimately is the correct type)?
Yes, it is possible.
The serialized XML/CSV/JSON data must contain identifiers to allow the deserializer to know what types of objects to create, since this can't be known beforehand. So that the deserializer can construct new object instances, the FactoryMethod design pattern is usually employed.
Deserialization is harder than serialization.
It depends on the serialization.
The BinarySerializer embeds type information into its output stream, so then what you describe would work perfectly. You get an object, and you could even do reflection on it, and then cast it to the correct type.
XML serialization doesn't work like that, which is why the XmlSerializer demands a type in its constructor.
You're best off in a scenario where the data may be one of a limited number of types, all of which inherit from a base type. Then you can give the base type (which is decorated with the known type attributes to let it know all about all the other types that it could be) and then deserialize the data to the standard base type, then inspect it.
CSV and JSON are even more difficult, since there isn't a lot of serialization support for them baked into the framework.
Not in any simple way. You'd have to write logic to analyze the data and decide what type its format most closely resembles.
Commonly yes. But it depends on which serialization do you use. The serialized data must contain metadata about the types of serialized objects. For example the xml serialization (System.Xml.Serialization) does not support this scenario.
精彩评论