在序列化派生类时序列化基类的属性

本文关键字:序列化 属性 基类 派生 | 更新日期: 2023-09-27 18:08:09

我有一个基类,有几个属性:

    // must include any derived classes here as known types or else they will throw errors on serialization
[KnownType(typeof(CollaborationEventMeasureDistance))]
[DataContract]
public partial class CollaborationEvent
{
    public bool HasBeenTransported { get; set; }
    public Guid MessageBoxGuid { get; set; } 
    public CollaborationEvent()
    {
        HasBeenTransported = false;
    }
}

和一个具有自己属性的派生类:

    public class CollaborationEventMeasureDistance : CollaborationEvent
{
    public Geometry Geometry { get; set; }
}

当我序列化派生类时,它的所有属性都被序列化,但它从基类继承的属性不是:

<CollaborationEvent i:type="CollaborationEventMeasureDistance">
  <Geometry xmlns:d4p1="http://schemas.datacontract.org/2004/07/ESRI.ArcGIS.Client.Geometry"
  i:type="d4p1:Polyline">
    <d4p1:spatialReference>
      <d4p1:wkid>26910</d4p1:wkid>
    </d4p1:spatialReference>
    <d4p1:paths>
      <d4p1:points>
        <d4p1:point>
          <d4p1:spatialReference>
            <d4p1:wkid>26910</d4p1:wkid>
          </d4p1:spatialReference>
          <d4p1:x>460892.23924271885</d4p1:x>
          <d4p1:y>5367682.5572773879</d4p1:y>
        </d4p1:point>
        <d4p1:point>
          <d4p1:spatialReference i:nil="true" />
          <d4p1:x>461001.35841108358</d4p1:x>
          <d4p1:y>5367648.5755294543</d4p1:y>
        </d4p1:point>
      </d4p1:points>
    </d4p1:paths>
  </Geometry>
</CollaborationEvent>
谁能指出我做错了什么?

我希望我的XML看起来更像:

    <CollaborationEvent i:type="CollaborationEventMeasureDistance">
  <HasBeenTransported>True</HasBeenTransported>
  <MessageBoxGuid>blah</MessageBoxGuid>
  <Geometry xmlns:d4p1="http://schemas.datacontract.org/2004/07/ESRI.ArcGIS.Client.Geometry"
  i:type="d4p1:Polyline">
    <d4p1:spatialReference>
      <d4p1:wkid>26910</d4p1:wkid>
    </d4p1:spatialReference>
    <d4p1:paths>
      <d4p1:points>
        <d4p1:point>
          <d4p1:spatialReference>
            <d4p1:wkid>26910</d4p1:wkid>
          </d4p1:spatialReference>
          <d4p1:x>460892.23924271885</d4p1:x>
          <d4p1:y>5367682.5572773879</d4p1:y>
        </d4p1:point>
        <d4p1:point>
          <d4p1:spatialReference i:nil="true" />
          <d4p1:x>461001.35841108358</d4p1:x>
          <d4p1:y>5367648.5755294543</d4p1:y>
        </d4p1:point>
      </d4p1:points>
    </d4p1:paths>
  </Geometry>
</CollaborationEvent>

谢谢

在序列化派生类时序列化基类的属性

假设您的Geometry类是可序列化的,请尝试这样做:

[DataContract, Serializable]
public class CollaborationEventMeasureDistance : CollaborationEvent  
{  
    [DataMember]
    public Geometry Geometry { get; set; }  
} 
[KnownType(typeof(CollaborationEventMeasureDistance))] 
[DataContract, Serializable]
public partial class CollaborationEvent 
{ 
    [DataMember]
    public bool HasBeenTransported { get; set; } 
    [DataMember]
    public Guid MessageBoxGuid { get; set; }  
    public CollaborationEvent() 
    { 
        HasBeenTransported = false; 
    } 
}