我需要de/serialize對象。但是,有時我需要以某種方式和其他方式序列化它們。De/Serialization模板
實施例:
public interface I : ISerializable {
String X { get; set; }
String Y { get; set; }
}
public class A : I
{
String X {...}
String Y {...}
String MyZ { ... }
}
public class B : I
{
String X {...}
String Y {...}
String MyS { ... }
}
有時我需要只使用X
字段序列化一個A a
或B b
對象,其它時候我只需要序列Y
字段。
請認識到這是一個小例子。實際情況下,真正存在的是我只想保存一些基本信息的對象,其他時間我需要保存其他字段。
這就像應用序列化模板。 任何想法?
編輯 相反的:
var f = new BinaryFormatter();
f.Context = new StreamingContext(StreamingContextStates.All, new []{ "X", "Y" });
用途:
var f = new BinaryFormatter();
f.Context = new StreamingContext(StreamingContextStates.All, TemplatesEnum.Template1);
所以,每一個對象是resposible爲自己以便根據TemplatesEnum
值序列化本身。
看看'[XmlIgnore]'屬性 –
你需要序列化它怎麼樣? XML? JSON?二進制? –