How avoid exception deserializing an invalid enum item?

前端 未结 3 860
花落未央
花落未央 2020-12-21 01:28

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:

p         


        
3条回答
  •  臣服心动
    2020-12-21 01:43

    I posted a similar question and have not found a simple method to catch the exception thrown when the deserializer encounters Apple in the XML file. I can catch a bunch of other exceptions during deserialiation for missing attributes or elements, but not for an invalid enum value. The invalid enum value (in your case Apple) blows me out of the deserialization.

    One possible solution is to implement IXMLSerializable on the Fruit class. When the IXMLSerailizable.ReadXML() method is called by the deserializer, you'll have to see what is being passed to you. When the value is "Apple" set the enum to GreenApple or RedApple based on some logic.

提交回复
热议问题