【发布时间】:2018-07-22 16:32:31
【问题描述】:
我有一个类只能有如下的唯一实例。这使得引用相等足以等同于对象。
虽然序列化很简单,但反序列化有点棘手,因为不能像我在下面所做的那样分配给this。如果仍然只想维护类的唯一实例,我该如何反序列化对象?
public sealed class MyClass :
ISerializable,
IXmlSerializable
{
private static readonly Dictionary<string, MyClass> Cache;
static MyClass() { /* build cache, use private constructor */ }
private MyClass(string name)
{
this.Name = name;
}
public string Name { get; }
public static MyClass Parse(string from)
=> Cache[from];
public void GetObjectData(SerializationInfo info, StreamingContext context)
=> throw new NotImplementedException();
public XmlSchema GetSchema() => null;
public void ReadXml(XmlReader reader)
{
reader.ReadStartElement();
this = Parse(reader.ReadContentAsString());
reader.ReadEndElement();
}
public MyClass(SerializationInfo info, StreamingContext context)
=> this = Parse(info.GetString(nameof(this.Name)));
public void WriteXml(XmlWriter writer)
=> throw new NotImplementedException();
}
【问题讨论】:
-
如果您能够更改您的课程代码,我强烈建议您将您的课程替换为三个不同的课程;一个用于序列化/反序列化,一个用于缓存,另一个用于您需要缓存的类。您的班级在这里承担不同的职责,这使其更加复杂。
标签: c# serialization