Programing

enum 값을 int로 직렬화하는 방법은 무엇입니까?

crosscheck 2020. 10. 18. 08:25
반응형

enum 값을 int로 직렬화하는 방법은 무엇입니까?


열거 형 값을 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();

이 대답 (다른 질문에 대한)은 enum이 기본값으로 int로 직렬화되어야 함을 나타내는 것처럼 보이지만 그렇게하지 않는 것 같습니다. 내 결과는 다음과 같습니다.

<?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 ")]"속성을 넣어 값으로 직렬화 할 수 있었지만 이것은 잘못된 것 같습니다.


대부분의 경우 사람들은 정수가 아닌 이름을 원합니다. 목적으로 shim 속성을 추가 할 수 있습니까?

[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있지만 그것은 많은 작업입니다.


가장 쉬운 방법은 다음과 같이 [XmlEnum] 속성을 사용하는 것입니다.

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

다음과 같이 XML로 직렬화됩니다 (부모 클래스가 CustomClass라고 가정).

<CustomClass>
  <EnumValue>2</EnumValue>
</CustomClass>

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의 내용은 다음과 같습니다.

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

DataContractSerializer에 대한 System.Runtime.Serialization.dll 어셈블리에 대한 참조가 필요합니다.


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
}

위의 접근 방식은 저에게 효과적이었습니다.


열거 형 옵션에 명시 적 비 순차적 값을 할당하기 때문에 한 번에 둘 이상의 값 (이진 플래그)을 지정할 수 있기를 원한다고 가정하므로 허용되는 대답은 유일한 옵션입니다. 사전 예약 통과 | PreBookingConfirmation은 정수 값 9를 가지며 serializer는이를 역 직렬화 할 수 없으며 shim 속성으로 캐스팅 할 수 있지만 잘 작동합니다. 아니면 3 값을 놓쳤을 수도 있습니다. :)


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.

참고URL : https://stackoverflow.com/questions/506368/how-do-i-serialize-an-enum-value-as-an-int

반응형