简体   繁体   中英

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).

I have a racing track which is made up of sections. Each section type inherits from a common TrackSection class. 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. 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). 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. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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