简体   繁体   中英

How to serialize only objects id

I have two classes

[Serializable]
public class SimpleClass
{
    public ComplexClass Parent { get; set; }
}

public class ComplexClass
{
    public Guid Id { get; set; }
    // Lots of stuff
}

... 
// and somewhere    
public static List<ComplexClass> ClassesList;

How to serialize SimpleClass so that only Guid is saved from complex class? How to deserialize it afterwards? Suppose I already have collection of ComplexClass es and only need to pick one by id.

I'm using XmlSerializer for serialization

包括名称空间System.Xml.Serialization,并在要在序列化中排除的字段或属性上添加属性[XmlIgnore]。

It would be possible to make a custom serialization of course using ISerializable , but if you want to keep it simple then something like this might work:

public class SimpleClass
{
    [XmlIgnore]
    public ComplexClass Parent { get; set; }

    public Guid ComplexClassId { 
        get { return Parent.Id; } 
        set { Parent = new ComplexClass(value); } 
    }
}

Or just mark the unwanted fields in ComplexClass using XmlIgnore .


I have changed my answer to use XmlIgnore instead of NonSerialized based on comment from LB Left the answer here because I think it still adds some info to Andypopa.

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