没有默认值的枚举的XML序列化 [英] XML Serialization of Enums Without Default Values

查看:145
本文介绍了没有默认值的枚举的XML序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举:

[DataContract]
public enum Relationship
{
    Spouse = 4,
    ResidesWith = 1,
    Parent = 2,
    Other = 3,
    PersonalGuarantor = 5,
    CoApplicant = 6
}

如您所见,零没有定义。我建立了我的程序,围绕在枚举中永远不会定义零的想法。这让我看看哪些已经从各种组合框设置,哪些被设置为一个空值。如果我将零设置为空值,那么没有办法分开这两个东西,我必须能够。

As you can see, zero is not defined. I built my program around the idea that zero would never be defined in enums. That allows me to see which ones have been set from various comboBoxes, and which ones were set to a null value. If I set zero as the null value, there is no way to tell those two things apart, and it essential that I be able to.

由于缺少默认状态,当我尝试序列化值时,我会收到错误。

Due to the lack of a default state, I get an error when I try to serialize the values.

有没有办法让我的xml序列化跳过枚举没有价值,还是一种避免这些错误的方法?我真的不想引入一个默认值。

Is there a way to have my xml serialize skip enums that have no value, or a way to avoid those errors? I really do not want to introduce a default value.

推荐答案

您需要使用0作为枚举值 - 使其成为无效的值,并检查(如你已经是)

You need to use 0 as an enum value - make it a value that is not valid and that you check for (as you are already).

[DataContract]
public enum Relationship
{
    Invalid = 0,
    Spouse = 4,
    ResidesWith = 1,
    Parent = 2,
    Other = 3,
    PersonalGuarantor = 5,
    CoApplicant = 6
}

不要忘记枚举是基于整数类型(它们的基类型) ,所以他们将永远有一个值(值类型不能为空),并将默认为 0

Don't forget that enumerations are based on an integer type (their base type), so they will always have a value (value types cannot be null) and will default to 0. Making this explicit will also make things clearer in your codebase.

Protip:您可以在枚举中使用否定的

Protip: You can use negative values in enums as well.

这篇关于没有默认值的枚举的XML序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆