【问题标题】:Custom Object collection Serialization自定义对象集合序列化
【发布时间】:2010-01-13 17:09:57
【问题描述】:

我正在尝试对由 UserData 对象组成的自定义集合 UserDataCollection 进行序列化。我想知道在实现Serialization时,实际的对象(UserData)是否也需要具有[Serializable]属性并继承自ISerializable接口?

我想序列化集合中的每个对象(UserData),它的所有属性和变量。

我现在有这个:

public class UserData : IEquatable<UserData>, IUser
{
/// some properties methods
}

    [Serializable()]
    class UserDataCollection : IEnumerable<UserData>, ISerializable
    {
        static List<UserData> Collection = new List<UserData>();
        IUser current;

        #region Properties
        public UserData Current
        {
            get 
            { 
                return (UserData)current; 
            }

            set
            {
                current = value;
            }
        }
        #endregion


        #region Constructors
        public UserDataCollection( IUser userdata )
        {
            this.current = userdata;
        }

        /// <summary>
        /// Deserialization Constructor
        /// </summary>
        /// <param name="SerializationInfo">This object holds a name-value pair for the             properties to be serialized</param>
        /// <param name="item"></param>
        public UserDataCollection(SerializationInfo serializationInfo, StreamingContext ctxt)
        {
            Current = (UserData)serializationInfo.GetValue("UserData", typeof(UserData)); <-- Can I just do this on the UserData object property or does it itself  also need to implement ISerializable?
        }
        #endregion

//more methods here...
}

集合将使用二进制序列化进行序列化。

【问题讨论】:

    标签: c# serialization collections


    【解决方案1】:

    是的,您的 UserData 类应标记为可序列化。它不必显式地从 ISerializable 继承,但如果你想自定义序列化当然可以。

    来自SerializableAttribute

    应用 SerializableAttribute 一个类型的属性来表明 这种类型的实例可以是 序列化。共同语言 运行时抛出 SerializationException 如果对象图中有任何类型 被序列化没有 SerializableAttribute 属性 已申请。

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 2012-11-29
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多