我想将我的枚举值序列化为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();
这个答案(对另一个问题)似乎表明枚举应该序列化为默认值,但它似乎并没有这样做.这是我的输出:
Confirmation
我已经能够通过在每个值上放置一个"[XmlEnum("X")]"属性来序列化为值,但这似乎是错误的.
最简单的方法是使用[XmlEnum]属性,如下所示:
[Serializable] public enum EnumToSerialize { [XmlEnum("1")] One = 1, [XmlEnum("2")] Two = 2 }
这将序列化为XML(比如父类是CustomClass),如下所示:
2
大多数时候,人们需要名字,而不是整数.您可以为此目的添加垫片属性吗?
[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
,但这是很多工作.
请参阅下面的完整示例控制台应用程序,以获得使用DataContractSerializer实现所需内容的有趣方法:
using System; using System.IO; using System.Runtime.Serialization; namespace ConsoleApplication1 { [DataContract(Namespace="petermcg.wordpress.com")] public class Request { [DataMember(EmitDefaultValue = false)] public RequestType request; } [DataContract(Namespace = "petermcg.wordpress.com")] public enum RequestType { [EnumMember(Value = "1")] Booking = 1, [EnumMember(Value = "2")] Confirmation = 2, [EnumMember(Value = "4")] PreBooking = 4, [EnumMember(Value = "5")] PreBookingConfirmation = 5, [EnumMember(Value = "6")] BookingStatus = 6 } class Program { static void Main(string[] args) { DataContractSerializer serializer = new DataContractSerializer(typeof(Request)); // Create Request object Request req = new Request(); req.request = RequestType.Confirmation; // Serialize to File using (FileStream fileStream = new FileStream("request.txt", FileMode.Create)) { serializer.WriteObject(fileStream, req); } // Reset for testing req = null; // Deserialize from File using (FileStream fileStream = new FileStream("request.txt", FileMode.Open)) { req = serializer.ReadObject(fileStream) as Request; } // Writes True Console.WriteLine(req.request == RequestType.Confirmation); } } }
调用WriteObject后,request.txt的内容如下:
2
您需要为DataContractSerializer引用System.Runtime.Serialization.dll程序集.