开发者

serialize each object in Object collection

开发者 https://www.devze.com 2022-12-16 20:16 出处:网络
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 o

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("开发者_StackOverflow中文版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] (i.e. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消