1
public class SerializablionHelper
{
  public SerializablionHelper()
  {
    this.Entities = new Collection<Base>();
  }

  public ICollection<Base> Entities { get; set; }
}

// [DataContract]
// [KnownType(typeof(A))]
// [KnownType(typeof(B))]
public abstract class Base
{
}

[DataContract]
public class A : Base
{
  public int IntTest { get; set; }

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

[DataContract]
public class B : Base
{
  [DataMember]
  public int IntTest { get; set; }

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


public static void Main(string[] args)
{
  var objectA = new A { IntTest = 5, StringTest = "TestA" };
  var objectB = new B { IntTest = 25, StringTest = "TestB" };

  var serList = new SerializablionHelper();
  serList.Entities.Add(objectA);
  serList.Entities.Add(objectB);
  var dcSerializer = new DataContractSerializer(typeof(SerializablionHelper));


  var xmlWriterSetting = new XmlWriterSettings() { Indent = true };
  using (var xmlWriter = XmlWriter.Create("C:\\test.xml", xmlWriterSetting))
  {
    dcSerializer.WriteObject(xmlWriter, serList);
  }
}

当我运行这段代码时,我得到了这个异常。

类型“XMLSerializer.Program+A”不能继承自未用 DataContractAttribute 或 SerializableAttribute 标记的类型。考虑使用 DataContractAttribute 或 SerializableAttribute 标记基类型“XMLSerializer.Program+Base”,或从派生类型中删除它们。

当我重新提交此代码时:

// [DataContract]
// [KnownType(typeof(A))]
// [KnownType(typeof(B))]

该代码将工作。

我无法将基类设为 DataContract 的问题。有没有办法让这段代码在不将 DataContract 添加到基类的情况下工作,或者我必须采取另一种序列化策略?

4

1 回答 1

0

我会这样做:

[DataContract]
[KnownType(typeof(A))]
[KnownType(typeof(B))]
public class SerializablionHelper
{
  public SerializablionHelper()
  {
    //this.Entities = new Collection<Base>();
  }
    // public ICollection<Base> Entities { get; set; }

  public Base A { get; set; }

  public Base B { get; set; }
}

public abstract class Base
{
}

[DataContract]
public class A : Base
{
  [DataMember]
  public int IntTest { get; set; }

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

[DataContract]
public class B : Base
{
  [DataMember]
  public int IntTest { get; set; }

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


public static void Main(string[] args)
{
  var objectA = new A { IntTest = 5, StringTest = "TestA" };
  var objectB = new B { IntTest = 25, StringTest = "TestB" };

  var serList = new SerializablionHelper { A = objectA, B = objectB };
  var dcSerializer = new DataContractSerializer(typeof(SerializablionHelper));


  var xmlWriterSetting = new XmlWriterSettings() { Indent = true };
  using (var xmlWriter = XmlWriter.Create("C:\\test.xml", xmlWriterSetting))
  {
    dcSerializer.WriteObject(xmlWriter, serList);
  }
}

我希望这将有所帮助。

于 2013-08-22T13:29:33.570 回答