2017-05-13 1 views
1

사용자가 XML에서 열거 형을 지정할 수 있도록 응용 프로그램을 디자인하려고합니다. 그리고이 응용 프로그램은 연결된 특정 메서드를 실행합니다. 그 enum (사전을 사용). 나는 XML의 열거 형 부분에 매달려있다.다른 수있는 일반 열거 형 클래스 직렬화 열거 형

string p = "C:\\testclass.xml"; 
TESTCLASS testclass = new TESTCLASS(Enummies.BigMethods.BIG_ONE); 
TestSerializer<TESTCLASS>.Serialize(p, testclass); 

System.InvalidOperationException: The type Enummies+BigMethods may not be used in this context. 

내 직렬화 방법은 다음과 같습니다 : 예외에 TestClass에 결과를 직렬화하려고

public class TESTCLASS 
{ 
    private Enum _MethodType; 

    [XmlElement(Order = 1, ElementName = "MethodType")] 
    public Enum MethodType 
    { 
     get { return _MethodType; } 
     set { _MethodType = value; } 
    } 
    public TESTCLASS() { } 

    public TESTCLASS(Enummies.BigMethods bigM) 
    { 
     MethodType = bigM; 
    } 
    public TESTCLASS(Enummies.SmallMethods smallM) 
    { 
     MethodType = smallM; 
    } 
} 

public class Enummies 
{ 
    public enum BigMethods { BIG_ONE, BIG_TWO, BIG_THREE } 
    public enum SmallMethods { SMALL_ONE, SMALL_TWO, SMALL_THREE } 
} 

그리고 나는 MethodType에 캐스팅/몇 가지 검사를 포함하여 시도

public class TestSerializer<T> where T: class 
{ 
    public static void Serialize(string path, T type) 
    { 
     var serializer = new XmlSerializer(type.GetType()); 
     using (var writer = new FileStream(path, FileMode.Create)) 
     { 
      serializer.Serialize(writer, type); 
     } 
    } 

    public static T Deserialize(string path) 
    { 
     T type; 
     var serializer = new XmlSerializer(typeof(T)); 
     using (var reader = XmlReader.Create(path)) 
     { 
      type = serializer.Deserialize(reader) as T; 
     } 
     return type; 
    } 
} 

Getter,하지만 같은 오류가 발생합니다.

public Enum MethodType 
    { 
     get 
     { 
      if (_MethodType is Enummies.BigMethods) return (Enummies.BigMethods)_MethodType; 
      if (_MethodType is Enummies.SmallMethods) return (Enummies.SmallMethods)_MethodType; 
      throw new Exception("UNKNOWN ENUMMIES TYPE"); 
     } 
     set { _MethodType = value; } 
    } 
+0

어떤 열거 형이 존재하는지 미리 알고 있습니까? – dbc

답변

1

내가 XmlSerializer으로 클래스를 직렬화 할 때, 내가 할 가장 안쪽의 예외가있다 :

Message="System.Enum is an unsupported type. Please use [XmlIgnore] attribute to exclude members of this type from serialization graph." 

이 자기 설명이다 : 당신이 유형이 추상 유형 System.Enum있는 멤버를 직렬화 할 수 없습니다.

당신은, 그러나, 발생할 수있는 값의 가능한 모든 종류의 [XmlInclude(typeof(T))]를 사용하여 정적으로 선언 된 경우에 한해 유형 System.Object의 멤버를 직렬화 할 수 있습니다.

<TESTCLASS xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <MethodType xsi:type="BigMethods">BIG_THREE</MethodType> 
</TESTCLASS> 

또는

<?xml version="1.0" encoding="utf-16"?> 
<TESTCLASS xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <MethodType xsi:type="SmallMethods">SMALL_TWO</MethodType> 
</TESTCLASS> 

을 주목 xsi:type 속성을 다음과 같이

// Include all possible types of Enum that might be serialized 
[XmlInclude(typeof(Enummies.BigMethods))] 
[XmlInclude(typeof(Enummies.SmallMethods))] 
public class TESTCLASS 
{ 
    private Enum _MethodType; 

    // Surrogate object property for MethodObject required by XmlSerializer 
    [XmlElement(Order = 1, ElementName = "MethodType")] 
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)] 
    public object MethodTypeObject 
    { 
     get { return MethodType; } 
     set { MethodType = (Enum)value; } 
    } 

    // Ignore the Enum member that cannot be serialized directly 
    [XmlIgnore] 
    public Enum MethodType 
    { 
     get { return _MethodType; } 
     set { _MethodType = value; } 
    } 
    public TESTCLASS() { } 

    public TESTCLASS(Enummies.BigMethods bigM) 
    { 
     MethodType = bigM; 
    } 
    public TESTCLASS(Enummies.SmallMethods smallM) 
    { 
     MethodType = smallM; 
    } 
} 

그리고 XML이 생성됩니다 다음과 같이 따라서 당신은 당신의 유형을 수정 할 수 있습니까? 요소가 명시 적으로 형식을 어설 션하는 데 사용할 수있는 것은 W3C standard attribute입니다. Microsoft는이 특성을 사용하여 here 설명 된 다형 요소에 대한 형식 정보를 나타냅니다.

샘플 fiddle.

가치 유형이 MethodObject (getter가 아닌)에 대한 설정자의 알려진 Enum 유형인지 확인할 수는 있지만 XML 직렬화에는 필요하지 않습니다.

+0

굉장합니다. XmlIncludes에서 잠재적 인 형식을 지정하는 한 System.Object의 멤버를 serialize 할 수 있다는 것을 알지 못했습니다. 왜 내가 본 것과 다른 예외가 생겼는지 궁금합니다. 또한 이러한 속성이 필요합니까? 나는 전에 그들을 본 적이 없다. "[Browsable (false), EditorBrowsable (EditorBrowsableState.Never), DebuggerBrowsable (DebuggerBrowsableState.Never)]" –

+1

@TalenKylon - 이러한 속성은 필요하지 않습니다. 디버거 및 속성 편집기에 대리 등록 정보가 표시되지 않도록합니다. 필자가 나열한 예외는 바깥 쪽 특성이 아니라 가장 안쪽 특성입니다. 또한 직렬화를 테스트하기 전에'[XmlInclude (typeof (Enummies.BigMethods)]] 속성을 추가했습니다. – dbc