DataContractSerializer反序列化已知类型

时间:2013-01-17 19:24:00

标签: c# deserialization datacontractserializer

我的对象结构如下:

[DataContract]
public abstract class Condition<T>
{
    [DataMember] public string Id { get; set; }
}

[DataContract(Name = "AttributeEqualTo", Namespace = "")]
public class AttributeEqualTo<T> : Condition<T>
{
    [DataMember] public string AttributeName { get; set; }
    [DataMember] public string ExpectedValue { get; set; }
}

[DataContract(Name = "AttributeNotEqualTo", Namespace = "")]
public class AttributeNotEqualTo<T> : AttributeEqualTo<T>
{
}

[CollectionDataContract(Name = "Conditions", Namespace = "")]
[KnownType("KnownTypes")]
public class ConditionSet<T> : Collection<Condition<T>>
{
    public static IEnumerable<Type> KnownTypes()
    {
        var knownTypes = new Collection<Type>
                             {
                                 typeof(AttributeEqualTo<T>),
                                 typeof(AttributeNotEqualTo<T>),
                             };
        return knownTypes;
    }
}

给出以下XML:

  <Conditions>
    <AttributeEqualTo>
      <Id>C1</Id>
      <AttributeName>Foo</AttributeName>
      <ExpectedValue>Bar</ExpectedValue>
    </AttributeEqualTo>
    <AttributeNotEqualTo>
      <Id>C2</Id>
      <AttributeName>Blah</AttributeName>
      <ExpectedValue>Value</ExpectedValue>
    </AttributeNotEqualTo>
  </Conditions>

当我反序列化它时,我希望得到一个条件集合,其中包括XML中定义的两个条件。我遇到的问题是我得到了收藏品,但它是空的。

我已经测试了单独反序列化条件的能力,它似乎工作正常。

我使用以下内容作为如何定义合同的参考,Data Contract Known Types

1 个答案:

答案 0 :(得分:0)

尝试删除泛型 - 这通常会破坏序列化。