Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

c# - How avoid exception deserializing an invalid enum item?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Leave Apple and mark it with the ObsoleteAttribute. That way, any code using Apple will generate a compiler warning.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...