简体   繁体   中英

serialize each object in Object collection

I have this code for serializing my custom collection of UserData Objects. However the current property only represents the item currently being used in the collection, so it only serializes that one object.

I want all the objects serialized in my collection, how would I go about that in the GetObjectData implementation of my Collection?

        public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
        {
            // Add the userdata object to SerializationInfo object
                info.AddValue("UserData", current);
        }

this is my deserialization constructor, I'm not sure this will then deserialize each object in the collection either.

public UserDataCollection(SerializationInfo serializationInfo, StreamingContext ctxt)
        {
            UserData data = (UserData)serializationInfo.GetValue("UserData", typeof(UserData));
              // Add to objects existing collection
            this.Add(data);
        }

How are you holding your objects behind the scenes? Do you have a List<T> field somewhere? Just serialize / deserialize that, and let it worry about it. To be honest, this should just happen if you mark the custom collection wrapper as [Serializable] and mark any unnecessary fields (such as current ) as [NonSerialized] (ie without you having to implement ISerializable ).

Note that in most scenarios I tend to advise against BinaryFormatter ; it is OK for sending short-lived (transient) messages, but I don't advise using it for storage purposes (in a file or in a database); you can get lots of versioning issues trying to deserialize at a later date.

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