如何将枚举值序列化为 int? [英] How do I serialize an enum value as an int?

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

问题描述

我想将我的枚举值序列化为一个整数,但我只得到了名称.

I want to serialize my enum-value as an int, but i only get the name.

这是我的(示例)类和枚举:

Here is my (sample) class and enum:

public class Request {
    public RequestType request;
}

public enum RequestType
{
    Booking = 1,
    Confirmation = 2,
    PreBooking = 4,
    PreBookingConfirmation = 5,
    BookingStatus = 6
}

还有代码(只是为了确保我没有做错)

And the code (just to be sure i'm not doing it wrong)

Request req = new Request();
req.request = RequestType.Confirmation;
XmlSerializer xml = new XmlSerializer(req.GetType());
StringWriter writer = new StringWriter();
xml.Serialize(writer, req);
textBox1.Text = writer.ToString();

这个answer(对另一个问题)似乎表明枚举应该默认序列化为整数,但它似乎并没有这样做.这是我的输出:

This answer (to another question) seems to indicate that enums should serialize to ints as default, but it doesn't seem to do that. Here is my output:

<?xml version="1.0" encoding="utf-16"?>
<Request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <request>Confirmation</request>
</Request>

通过在每个值上放置[XmlEnum("X")]"属性,我已经能够将其序列化为值,但这似乎是错误的.

I have been able to serialize as the value by putting an "[XmlEnum("X")]" attribute on every value, but this just seems wrong.

推荐答案

大多数时候,人们想要的是名字,而不是整数.您可以为此目的添加 shim 属性吗?

Most of the time, people want names, not ints. You could add a shim property for the purpose?

[XmlIgnore]
public MyEnum Foo {get;set;}

[XmlElement("Foo")]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public int FooInt32 {
    get {return (int)Foo;}
    set {Foo = (MyEnum)value;}
}

或者您可以使用 IXmlSerializable,但这需要大量工作.

Or you could use IXmlSerializable, but that is lots of work.

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

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