本文介绍了XmlSerializer的:如何反序列化已经不存在一个枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用XmlSerializer这个类保存到一个文件中。这个类有一个字符串和一个枚举,如下所示:

I am using the XMLSerializer to save this class to a file. The class has a string and an enum as shown below:

public class IOPoint
{
     string Name {get; set;}
     TypeEnum {get; set;}
}


public enum TypeEnum
{
    Temperature,
    Pressure,
    Humidity,
}

在连载它看起来像这样。

When serialized it looks like this.

<IOPoint>
  <Name>Relative Humidity</Name>
  <TypeEnum>Humidity</TypeEnum>
</IOPoint>



我已经和序列化,没有任何问题了几个版本的反序列化此对象。我不再想支持湿度,所以我从枚举删除它。然而,从XML反序列化的时候,因为在外地TypeEnum,湿度值,是不是为TypeEnum有效值这会导致异常。这是有道理的,但如何处理?

I've been serializing and deserializing this object with no problems for several versions. I no longer want to support Humidity, so I removed it from the enum. However, this causes an exception when deserializing from XML because the value in the TypeEnum field, Humidity, is not a valid value for the TypeEnum. This makes sense, but how to handle this?

我想要做的就是忽略这个错误。并留下了一个空值。我试过实现OnUnknownElement XmlDeserilizationEvent类。不幸的是,这并没有抓住这个错误。

What I'd like to do is just ignore this error. And leave the value as null. I've tried implementing the OnUnknownElement XmlDeserilizationEvent class. Unfortunately, this does not catch this error.

如何捕捉和忽略这个错误任何想法(我可以清理的反序列化完成后)。

Any ideas on how to catch and ignore this error (I can clean up after the deserialization is complete).

米奇

推荐答案

您可以标记过时成员

public enum TypeEnum
{
    Temperature,
    Pressure,
    [Obsolete]
    Humidity
}

这篇关于XmlSerializer的:如何反序列化已经不存在一个枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:19