For simplicity purposes here, I will show my sample code using fruit. In actuality I am doing something more meaningful (we hope). Let say we have an enum:
public enum FruitType
{
Apple,
Orange,
Banana
}
And a class:
[Serializable]
public class Fruit
{
public FruitType FruitType { get; set; }
public Fruit(FruitType type)
{
this.FruitType = type;
}
}
We can serialize and de-serialize it. Now, lets revise the enum, so that it is now:
public enum FruitType
{
GreenApple,
RedApple,
Orange,
Banana
}
When de-serializing previously serialized objects, you get a System.InvalidOperation
exception as Apple
(original enum item) is not valid. The object does not get de-serialized.
One way I was able to resolve this was to give the FruitType
property in the Fruit
class a different name when it gets serialized as follows:
[XmlElement(ElementName = "Mode")]
public FruitType FruitType { get; set; }
Now, during de-serialization the old property gets ignored as it is not found. I would like to know if there is a way to ignore/skip invalid enum items during de-serialization, so that no exception is thrown and the object still gets de-serialized.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…