如何避免异常反序列化无效的枚举项? [英] 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
}
和一个班级:
[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
}
反序列化先前序列化的对象时,您会得到 System.InvalidOperation
异常,作为 Apple
(原始枚举项)无效。该对象不会反序列化。
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.
我能够解决此问题的一种方法是提供 FruitType
Fruit
类中的属性按如下所示进行序列化时使用不同的名称:
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.
推荐答案
保留 Apple
并用 ObsoleteAttribute
进行标记。这样,使用 Apple
的任何代码都将生成编译器警告。
Leave Apple
and mark it with the ObsoleteAttribute
. That way, any code using Apple
will generate a compiler warning.
这篇关于如何避免异常反序列化无效的枚举项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!