Skip to main content
 首页 » 编程设计

c#之具有继承变化的DataContract

2024年02月20日13findumars

我正在使用 DataContracts 序列化对象。假设我序列化了一个这样结构的数据:

[DataContract] 
public class Dog : IExtensibleDataObject 
{ 
    [DataMember] 
    public int age; 
 
    [DataMember] 
    public string name; 
 
    ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; } 
} 

现在我正在改变我的架构,我想用这个类读取以前序列化的数据:

[DataContract] 
[KnownType(typeof(Dog))] 
public class Animal : IExtensibleDataObject 
{ 
    [DataMember] 
    public string name; 
 
    ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; } 
} 
 
[DataContract] 
public class Dog : Animal 
{ 
    [DataMember] 
    public int age; 
} 

但我得到 name = null。我知道这取决于顺序:文件首先保存为年龄,然后从名称开始读取,因为它在基类上。
有没有办法处理这个问题,也许是通过更改顺序?

请您参考如下方法:

我认为这是不可能的。

以前的xml应该是

<dog> 
    <name>Bob</name> 
    <age>10</age> 
</dog> 

现在期待

<animal> 
    <name>Bob</name> 
    <dog> 
        <age>10</age> 
    </dog> 
</animal> 

该属性在新 DataContract 上序列化的任何内容中都更高。 更改继承层次结构是 IExtensibleDataObject 方法的重大更改。

The use of inheritance together with data contracts is allowed, provided that inheritance is not used as a versioning mechanism and that certain rules are followed. If a type derives from a certain base type, do not make it derive from a different base type in a future version (unless it has the same data contract). There is one exception to this: you can insert a type into the hierarchy between a data contract type and its base type, but only if it does not contain data members with the same names as other members in any possible versions of the other types in the hierarchy. In general, using data members with the same names at different levels of the same inheritance hierarchy can lead to serious versioning problems and should be avoided.

更多信息在 Best Practices: Data Contract Versioning

编辑 1:

您或许可以尝试在 Animal 中将 Name 设为虚拟并在 Dog 中覆盖它?或者一些疯狂的方法来强制序列化的新版本在 dog 下命名。即类似的东西,

[DataContract]  
[KnownType(typeof(Dog))]  
public class Animal : IExtensibleDataObject  
{ 
    public virtual string name;  
 
    ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; }  
}  
 
[DataContract]  
public class Dog : Animal  
{  
    [DataMember]  
    public override string name;  
 
    [DataMember]  
    public int age;  
}