【问题标题】:Serialize a derived class without access to base class序列化派生类而不访问基类
【发布时间】:2014-05-21 16:52:58
【问题描述】:

我需要在我的 Windows Phone 7 项目中序列化一个派生类以获得墓碑状态。 但我无权访问基类的代码 - 由库公开 -。

//don't have access to this class
public class A
{
     public string member1 {get;set;}
}

[DataContract]
public class B : A
{
     public B(){}; //CTOR

     [DataMember]
     public string member2 {get;set;}
}

当系统尝试序列化时(我将其保存到 PhoneApplicationPage.State => 所以它是自动序列化的):它不起作用,异常 (InvalidDataContractException) 说 “类型'B'不能继承自未使用 DataContractAttribute 或 SerializableAttribute 标记。考虑使用 DataContractAttribute 或 SerializableAttribute 标记基类型“A”,或从派生类型中删除它们。”

我应该实现自定义序列化程序吗?我该怎么做(在 Windows Phone 7 中)

【问题讨论】:

    标签: wpf windows-phone-7 serialization


    【解决方案1】:

    您可以拥有一个该类型的成员变量,并通过自定义 getter 和 setter 公开库类成员的属性,而不是从库类派生:

    [DataContract]
    public class MyClass
    {
        BaseClass Wrapped { get; set; }
    
        public MyClass()
        {
            Wrapped = new BaseClass( );
        }
    
        [DataMember]
        public string member1
        {
            get { return Wrapped.member1; }
            set { Wrapped.member1= value; }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多