如何在序列化时维护对象引用



好吧,我有点不清楚这是如何工作的,或者是否可能。我想序列化Child类,但当Parent对象执行Child.MyPparent字段时,我实际上不想序列化它。。。我只是希望引用被序列化。这可能吗?我该怎么做?

public class Parent
{ 
    public Child New()
    {
        return new Child(this);
    }
}
public class Child
{
    public Parent MyParent;
    public Child(Parent parent)
    {
        MyParent = parent;
    }
}

编辑:我使用DataContractSerializer,但如果需要,我不反对切换到其他东西。

XMLIgnoreAttribute可以应用于不需要序列化的字段。例如,

public class Child
{
    [XmlIgnore]
    public Parent MyParent;
    public Child(Parent parent)
    {
        MyParent = parent;
    }
}

但是,就序列化对字段的引用而言,您必须提供更多关于如何持久化引用所指向的对象的信息。您为什么不序列化Parent成员(在您的情况下)?序列化所有需要的公共成员是很常见的。

如果您只想使用序列化进行克隆,那么应该可以使用以下方法:

private static Parent Clone(Parent parent)
{
    Parent parentClone = null;
    lock (m_lock) // serialize cloning.
    {
        IFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream();
        using (stream)
        {
            formatter.Serialize(stream, parent);
            stream.Seek(0, SeekOrigin.Begin);
            parentClone = (Parent)formatter.Deserialize(stream);
        }
    }
    return parentClone;
}

听起来您可能需要实现自己的序列化和反序列化功能。

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.getobjectdata.aspx

以下是MSDN 的摘录

[Serializable]
    public class Person : ISerializable
    {
        private string name_value;
        private int ID_value;
        public Person() { }
        protected Person(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
                throw new System.ArgumentNullException("info");
            name_value = (string)info.GetValue("AltName", typeof(string));
            ID_value = (int)info.GetValue("AltID", typeof(int));
        }
        [SecurityPermission(SecurityAction.LinkDemand,Flags = SecurityPermissionFlag.SerializationFormatter)]
        public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
                throw new System.ArgumentNullException("info");
            info.AddValue("AltName", "XXX");
            info.AddValue("AltID", 9999);
        }
        public string Name
        {
            get { return name_value; }
            set { name_value = value; }
        }
        public int IdNumber
        {
            get { return ID_value; }
            set { ID_value = value; }
        }
    }

最新更新