How do I serialize an enum value as an int?

后端 未结 6 688
长发绾君心
长发绾君心 2020-11-28 05:48

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 RequestTy         


        
相关标签:
6条回答
  • 2020-11-28 06:26

    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.

    0 讨论(0)
  • 2020-11-28 06:30

    The easiest way is to use [XmlEnum] attribute like so:

    [Serializable]
    public enum EnumToSerialize
    {
        [XmlEnum("1")]
        One = 1,
        [XmlEnum("2")]
        Two = 2
    }
    

    This will serialize into XML (say that the parent class is CustomClass) like so:

    <CustomClass>
      <EnumValue>2</EnumValue>
    </CustomClass>
    
    0 讨论(0)
  • 2020-11-28 06:32

    Please see the full example Console Application program below for an interesting way to achieve what you're looking for using the 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);
            }
        }
    }
    

    The contents of request.txt are as follows after the call to WriteObject:

    <Request xmlns="petermcg.wordpress.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <request>2</request>
    </Request>
    

    You'll need a reference to the System.Runtime.Serialization.dll assembly for DataContractSerializer.

    0 讨论(0)
  • 2020-11-28 06:42
    using System.Xml.Serialization;
    
    public class Request
    {    
        [XmlIgnore()]
        public RequestType request;
    
        public int RequestTypeValue
        {
          get 
          {
            return (int)request;
          } 
          set
          {
            request=(RequestType)value; 
          }
        }
    }
    
    public enum RequestType
    {
        Booking = 1,
        Confirmation = 2,
        PreBooking = 4,
        PreBookingConfirmation = 5,
        BookingStatus = 6
    }
    

    The above approach worked for me.

    0 讨论(0)
  • 2020-11-28 06:44

    Since you are assigning explicit non-sequential values to the enum options I am assuming you want to be able to specify more than one value at a time (binary flags), then the accepted answer is your only option. Passing in PreBooking | PreBookingConfirmation will have an integer value of 9 and the serializer will not be able to deserialize it, casting it with a shim property however will work well. Or maybe you just missed the 3 value :)

    0 讨论(0)
  • 2020-11-28 06:50

    Take a look at the System.Enum class. The Parse method converts a string or int representation into the Enum object and the ToString method converts the Enum object to a string which can be serialized.

    0 讨论(0)
提交回复
热议问题