我只熟悉序列化的基础知识,现在我已经使用它了。 我有一个现有的报告系统,其中包含 ReportBase 抽象类和从基类派生的多个报告。 它们各自在构造函数中指定了不同的报告参数,有时还指定了额外的方法。 是否可以序列化任何派生类,然后在不知道派生类类型的情况下进行反序列化。
或者我可以通过反思做一些事情来实现它。 我可能会将序列化对象存储到数据库中,以便可以将报告类添加到我认为的另一个字段中。
I am only familiar with the basics of serialization, now I have a use for it. I have an existing reporting system with a ReportBase abstract class and multiple reports deriving from the base class. These each have different report parameters specified in the constructor and occasionally extra methods. Is it possible to serialize any of the derived classes and then later deserialize without knowing the derived class type.
Alternatively could I do something with reflection to achieve it. I will probably be storing the serialized objects to a database so could add the report class to another field I suppose.
发布评论
评论(1)
是的,在不知道对象的实际类型的情况下当然可能进行反序列化。 事实上,您不需要了解有关类型的任何信息即可进行反序列化。 从二进制意义上来说,反序列化只是将字节数组转换为原始类型,并将引用作为对象返回。 之后您可以自由地将其转换为实例的任何合法类型。
例如,以下代码会将流反序列化为对象并将引用转换为 ReportBase 类型。
请注意上面我说这是可能的。 为了使其工作,流必须指向 ReportBase 派生类的有效序列化实例,并且该类必须符合序列化规则。
创建一个预期可序列化但不可序列化的类非常容易: http://blogs.msdn.com/jaredpar/archive/2009/03/31/is-it-serialized.aspx
Yes, it's certainly possible to deserialize without knowing the actual type of the object. In fact, you don't need to know anything about the type in order to deserialize. Deserialization, in the binary sense, simply converts an array of bytes into the original type and returns the reference as object. You're free to cast this to any legal type for the instance afterwards.
For example, the following code will deserialize the stream into an object and convert the reference to a ReportBase type.
Note above that I said it's possible. In order for this to work, stream must point to a valid serialized instance of ReportBase derived class and that class must conform to the rules of serialization.
It's very easy to create a class which is intended to be, but is not serializable: http://blogs.msdn.com/jaredpar/archive/2009/03/31/is-it-serializable.aspx