代码之家  ›  专栏  ›  技术社区  ›  Jeremy

可序列化类继承自具有自己类型的属性的接口

  •  0
  • Jeremy  · 技术社区  · 15 年前

    我有一个接口,它定义了与接口类型相同的属性。

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

    现在,如果我声明一个类并从接口继承,我需要创建名为parent的属性。我希望我的类是可序列化的,以便在web服务中使用,但是当以这种方式使用接口时,接口是不可序列化的,那么我应该如何处理IMyInterface类型的属性?我确实希望该属性序列化。

    2 回复  |  直到 15 年前
        1
  •  1
  •   schup    14 年前

    .. 即使有单子。

    (其实这不好玩…)

    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; }
    }
    
        2
  •  0
  •   Arthur    15 年前

    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;
        }
    }
    

    编辑:我用这个代码测试了这个问题。没用。我想,xmlement将与“object”类型的属性执行相同的操作。

    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 因为它是一个接口。”