Programmatically set properties to exclude from serialization
Is it possible to programmatically set that you want to exclude a property from serialization?
Example:
- When de-serializing, I want to load up a开发者_运维知识库n ID field
- When serializing, I want to NOT output the ID field
I believe there are three options here:
Use XmlIgnore attribute. The downside is that you need to know in advance which properties you want the xmlserializer to ignore.
Implement the IXmlSerializable interface. This gives you complete control on the output of XML, but you need to implement the read/write methods yourself.
Implement the ICustomTypeDescriptor interface. I believe this will make your solution to work no matter what type of serialization you choose, but it is probably the lengthiest solution of all.
It depends on serialization type. Here full example for doing this with BinaryFormatter:
You may use OnDeserializedAttribute:
[Serializable]
class SerializableEntity
{
[OnDeserialized]
private void OnDeserialized()
{
id = RetrieveId();
}
private int RetrievId() {}
[NonSerialized]
private int id;
}
And there is another way to do this using IDeserializationCallback:
[Serializable]
class SerializableEntity: IDeserializationCallback
{
void IDeserializationCallback.OnDeserialization(Object sender)
{
id = RetrieveId();
}
private int RetrievId() {}
[NonSerialized]
private int id;
}
Also you may read great Jeffrey Richter's article about serialization: part 1 and part 2.
If you are serializing to XML, you can use XMLIgnore
As in:
class SomeClass
{
[XmlIgnore] int someID;
public string someString;
}
An old post, but I found ShouldSerialize pattern http://msdn.microsoft.com/en-us/library/53b8022e%28VS.71%29.aspx That is really HELPFUL!!!
If you want to include field during serialization but ignore it during deserialization then you can use OnDeserializedAttribute to run a method which will set default value for ID field.
If you're using XML serialization, use the [XmlIgnore]
attribute. Otherwise, how to ignore a particular property is defined by the serializer itself.
The NonSerializedAttribute attribute.
http://msdn.microsoft.com/en-us/library/system.nonserializedattribute.aspx
精彩评论