将枚举序列化为int

时间:2010-01-12 21:05:15

标签: .net enums xml-serialization

我希望通过一个Web服务返回以下类,该服务包含一个枚举类型作为其成员之一。

[Serializable, XmlRoot("GeoCoordinate")]
public class GeoCoordinate
{
    public enum AccuracyLevel
    {
        Unknown = 0,
        Country = 1,
        Region = 2,
        SubRegion = 3,
        Town = 4,
        PostalCode = 5,
        Street = 6,
        Intersection = 7,
        Address = 8,
        Premise = 9
    }

    private AccuracyLevel _accuracy;

    // ... more members


    public AccuracyLevel Accuracy
    {
        get { return _accuracy; } 
        set { _accuracy = value;}
    }
}

这样可以正常工作,但会以以下形式返回结果:

<!-- ... -->
<Accuracy>Unknown or Country or Region or SubRegion or Town or 
  PostalCode or Street or Intersection or Address or Premise</Accuracy>
<!-- ... -->

我希望它只返回一个整数,而不是代表枚举的字符串。这可以在不改变GeoCoordinate.Accuracy的类型的情况下完成吗?

3 个答案:

答案 0 :(得分:4)

虽然这是一个hack,但我认为在每个枚举成员中使用XmlEnumAttribute在这种情况下最适合。如果这个枚举要大得多,那么在Accuracy属性上使用XmlIgnore可能会更好,并在该类的另一个答案中描述的方法中为该类添加一个额外的int属性。

Usng XmlEnumAttribute意味着只需要修改枚举本身,并且无论在何处使用,xml都会像int一样序列化。

    public enum AccuracyLevel
    {
        [XmlEnum("0")] Unknown = 0,
        [XmlEnum("1")] Country = 1,
        [XmlEnum("2")] Region = 2,
        [XmlEnum("3")] SubRegion = 3,
        [XmlEnum("4")] Town = 4,
        [XmlEnum("5")] PostalCode = 5,
        [XmlEnum("6")] Street = 6,
        [XmlEnum("7")] Intersection = 7,
        [XmlEnum("8")] Address = 8,
        [XmlEnum("9")] Premise = 9
    }

答案 1 :(得分:3)

我相信你需要在枚举上使用[XmlIgnore],并创建一个返回整数值的第二个属性:

[XmlRoot("GeoCoordinate")]
public class GeoCoordinate
{
    public enum AccuracyLevel
    {
        Unknown = 0,
        Country = 1,
        Region = 2,
        SubRegion = 3,
        Town = 4,
        PostalCode = 5,
        Street = 6,
        Intersection = 7,
        Address = 8,
        Premise = 9
    }

    private AccuracyLevel _accuracy;

    // ... more members


    [XmlIgnore]
    public AccuracyLevel Accuracy
    {
        get { return _accuracy; } 
        set { _accuracy = value;}
    }

    [XmlElement("AccuracyLevel")]
    public int AccuracyLevelInt
    {
        get {return (int) AccuracyLevel;}
        set {AccuracyLevel = (AccuracyLevel) value;}
    }
}

请注意,XML序列化程序不使用[Serializable]

另请注意,AccuracyLevelInt属性可能未正确实现。我现在正在研究它。

答案 2 :(得分:1)

使用[Serializable][DataContract]装饰枚举。这两个属性之间存在一些差异,请务必查看(this blog post可能会有所帮助)。并使用[EnumMember]标记各个枚举项。我从未检查过程中枚举的内容,但这样做会确保它到达另一端,并且还会确保在生成客户端代理时它会被拾取。