2009-11-25 2 views
0

인터페이스와 동일한 유형의 속성에 대한 정의가있는 인터페이스가 있습니다.자체 형식의 속성을 사용하여 인터페이스에서 상속받을 수있는 Serializable 클래스

public interface IMyInterface 
{ 
    IMyInterface parent 
    { 
     get; 
     set; 
    } 
} 

이제 클래스를 선언하고 인터페이스에서 상속하는 경우 parent라는 속성을 만들어야합니다. 웹 서비스에서 사용하기 위해 클래스를 직렬화 할 수 있지만 인터페이스는 직렬화 할 수 없으므로 IMyInterface 유형의 속성에 대해 어떻게해야합니까? 그 속성이 직렬화되기를 바랄뿐입니다.

답변

0

테스트되지 않음 : XmlSerialization을 사용하면 알려진 모든 구현에 대해 [XmlElement] 특성을 사용하여 속성을 꾸밀 수 있습니다.

public interface IMyInterface 
{ 
    [XmlElement(Type=typeof(App.Projekt), ElementName="Projekt")] 
    [XmlElement(Type=typeof(App.Person), ElementName="Person")] 
    [XmlElement(Type=typeof(App.Task), ElementName="Task")] 
    IMyInterface parent 
    { 
     get; 
     set; 
    } 
} 

테스트되지 않음 - 인터페이스에서 작동하는지 여부는 알 수 없습니다.

편집 :이 코드로이 문제를 테스트했습니다. 그것은 작동하지 않았다. XmlElement는 "object"유형의 Property와 동일한 기능을 수행 할 것이라고 생각했습니다.

public interface IMyInterface 
{ 
    IMyInterface Parent { get; set; } 
    string Name { get; set; } 
} 

public class ClassA : IMyInterface 
{ 
    [XmlElement(Type = typeof(ClassA), ElementName = "ClassA")] 
    [XmlElement(Type = typeof(ClassB), ElementName = "ClassB")] 
    [XmlElement(Type = typeof(ClassC), ElementName = "ClassC")] 
    public IMyInterface Parent { get; set; } 
    public string Name { get; set; } 

    public string AProperty { get; set; } 
} 

public class ClassB : IMyInterface 
{ 
    [XmlElement(Type = typeof(ClassA), ElementName = "ClassA")] 
    [XmlElement(Type = typeof(ClassB), ElementName = "ClassB")] 
    [XmlElement(Type = typeof(ClassC), ElementName = "ClassC")] 
    public IMyInterface Parent { get; set; } 
    public string Name { get; set; } 

    public string BProperty { get; set; } 
} 

public class ClassC : IMyInterface 
{ 
    [XmlElement(Type = typeof(ClassA), ElementName = "ClassA")] 
    [XmlElement(Type = typeof(ClassB), ElementName = "ClassB")] 
    [XmlElement(Type = typeof(ClassC), ElementName = "ClassC")] 
    public IMyInterface Parent { get; set; } 
    public string Name { get; set; } 

    public string CProperty { get; set; } 
} 

예외였다

"가 인터페이스 때문에 멤버 TestXMLSerializer.ClassA.Parent 형 TestXMLSerializer.IMyInterface 의 직렬화 할 수 없습니다."

+0

는 (음, 사실은 재미 없어 ...) 작동 표시되지 않습니다. 나도 운이 XmlInclude 속성을 사용하여 시도했다 – Jeremy

1

재미있는 점은 인터페이스 클래스를 추상 클래스로 바꾸면 작동한다는 것입니다. .. 목록도 있습니다.

public class Root 
{ 
    [XmlElementAttribute("ClassA", typeof(ClassA))] 
    [XmlElementAttribute("ClassB", typeof(ClassB))] 
    [XmlElementAttribute("ClassC", typeof(ClassC))] 
    public List<IMyInterface> Items { get; set; } 
} 


public abstract class IMyInterface 
{ 
    IMyInterface Parent { get; set; } 
    string Name { get; set; } 
} 
+0

그 위대한 작품! 고맙습니다! :) –

관련 문제