如何将枚举值序列化为int? [英] How do I serialize an enum value as an int?
问题描述
这是我的(示例)类和枚举:
我想将序列化为枚举值作为int > public class Request {
public RequestType request;
}
public enum RequestType
{
Booking = 1,
确认= 2,
PreBooking = 4,
PreBookingConfirmation = 5,
BookingStatus = 6
}
而代码确保我没有做错了)
请求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();
这个答案(到另一个问题)似乎表明枚举应该序列化为int作为默认值,但它似乎没有这样做。这是我的输出:
<?xml version =1.0encoding =utf-16?>
<请求xmlns:xsi =http://www.w3.org/2001/XMLSchema-instancexmlns:xsd =http://www.w3.org/2001/XMLSchema>
< request>确认< / request>
< / Request>
我已经能够通过放置[XmlEnum(X)] 属性在每个值,但这只是似乎错误。
大多数时候,人们想要名字,而不是int。您可以为此目的添加一个垫片属性?
[XmlIgnore]
public MyEnum Foo {get; set;}
[XmlElement(Foo)]
[EditorBrowsable(EditorBrowsableState.Never),Browsable(false)]
public int FooInt32 {
get {return )Foo;}
set {Foo =(MyEnum)value;}
}
或者你可以使用 IXmlSerializable
,但这是很多工作。
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();
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>
I have been able to serialize as the value by putting an "[XmlEnum("X")]" attribute on every value, but this just seems wrong.
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;}
}
Or you could use IXmlSerializable
, but that is lots of work.
这篇关于如何将枚举值序列化为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!