加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

.net – 如何将枚举值序列化为int?

发布时间:2020-12-16 08:14:29 所属栏目:百科 来源:网络整理
导读:我想将我的枚举值序列化为一个int,但我只得到名称。 这里是我的(样本)类和枚举: public class Request { public RequestType request;}public enum RequestType{ Booking = 1,Confirmation = 2,PreBooking = 4,PreBookingConfirmation = 5,BookingStatus =
我想将我的枚举值序列化为一个int,但我只得到名称。

这里是我的(样本)类和枚举:

public class Request {
    public RequestType request;
}

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

和代码(只是为了确保我不会做错了)

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();

This answer(到另一个问题)似乎表明枚举应该序列化为ints作为默认,但它似乎不这样做。这里是我的输出:

<?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“)]”属性,但这似乎是错误的。

大多数时候,人们想要名字,而不是int。您可以为此目的添加垫片属性?
[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,但这是很多工作。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读