[英]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? 如何序列化
SimpleClass
以便从复杂类中仅保存Guid
? How to deserialize it afterwards? 之后如何反序列化? Suppose I already have collection of
ComplexClass
es and only need to pick one by id. 假设我已经有了
ComplexClass
集合, ComplexClass
id选择一个即可。
I'm using XmlSerializer
for serialization 我正在使用
XmlSerializer
进行序列化
包括名称空间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: 当然可以使用
ISerializable
进行自定义序列化,但是如果您想使其简单,则可以使用以下方法:
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
. 或者只是使用
XmlIgnore
在ComplexClass中标记不需要的字段。
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. 我已根据LB的评论将答案更改为使用
XmlIgnore
而不是NonSerialized
,因为我认为它仍然为Andypopa添加了一些信息,所以将答案留在此处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.