简体   繁体   English

C#中的自定义序列化程序和继承

[英]Custom serializer and inheritence in C#

I'm learning about serialization in C# and I have the basics down, but now I am trying something a little more complicated and I'm looking for some pointers on best practice (I can achieve what I want, I just want to know the 'right'/easiest/least code/most robust method of doing it). 我正在学习有关C#的序列化的知识,但我掌握了一些基础知识,但是现在我正在尝试一些更复杂的事情,并且正在寻找最佳实践的指导(我可以实现我想要的,我只是想知道“正确” /最简单/最少代码/最可靠的方法)。

I have a racing track which is made up of sections. 我有一条由路段组成的赛道。 Each section type inherits from a common TrackSection class. 每个节类型都继承自一个常见的TrackSection类。 The TrackSection class holds a lot of data on geometry and other things that I don't want to save out and it needs some context information when the constructor is called, so I have implemented the ISerializable interface and provided my own methods to handle (de)serialization. TrackSection类保存了大量关于几何图形和其他我不想保存的数据,并且在调用构造函数时需要一些上下文信息,因此我实现了ISerializable接口并提供了自己的方法来处理(de )序列化。 The classes that inherit from TrackSection are a lot simpler, and I would be happy for all their fields to be serialized automatically, but I assume that since the base class is ISerializable they probably need to do it manually as well (I have added the deserialization constructor and call the base class's deserialization constructor in each). 从TrackSection继承的类要简单得多,我很乐意将其所有字段自动序列化,但是我假设由于基类是ISerializable,所以它们可能也需要手动进行(我添加了反序列化构造函数,并在每个实例中调用基类的反序列化构造函数)。 When it comes to serializing though I'm not sure what to do, I would have expected ISerializable's GetObjectData() method to be virtual so I could extend the serialization in sub-classes. 关于序列化,尽管我不确定该怎么做,我希望ISerializable的GetObjectData()方法是虚拟的,因此可以在子类中扩展序列化。 Do I simply need to implement my own virtual method that is called from the base class's GetObjectData(), or am I going about this all wrong? 我是否只需要实现从基类的GetObjectData()调用的我自己的虚拟方法,还是我将这一切搞错了?

As I say, I have it working but any better solution or any general tips about what I'm doing would be much appreciated, as I can't help but feel my solution is a little more complicated than it needs to be. 就像我说的那样,我可以使用它,但是任何更好的解决方案或关于我正在做的事情的任何一般性提示都将不胜感激,因为我不禁感到自己的解决方案比需要的复杂。 Thanks. 谢谢。

除非您在需要实现ISerializable的事情上做某件事,否则,您可以改为使用Serializable属性标记该类,并将不需要序列化的字段标记为NonSerialized

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM