6

I am failing to save a list of Animals to disk with XML serialization.

I am getting Exception:Thrown: "The type AnimalLibrary.Animals.Mammals.Dog was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically." (System.InvalidOperationException)

If I try the commented code with the "Dog" it will work just as expected and the XML is generated. But the same dog sent in as the only element in the List does not work.

    [XmlElement("animalList")]
    public List<Animal> animalList = new List<Animal>();

public bool SaveBinary(string fileName)
    {
        Mammals.Dog dog = (Mammals.Dog)animalList[0];

        //IObjectSerializer<Mammals.Dog> obj = new XMLObjectSerializer<Mammals.Dog>();
        IObjectSerializer<List<Animal>> obj = new XMLObjectSerializer<List<Animal>>();

        bool saved = obj.SaveFile(fileName, animalList);
        if (saved)
            return true;

        return false;
    }

XML serializer

public bool SaveFile(string fileName, T objectToSerialize)
    {
        try
        {
            //Will overwrite old file
            XmlSerializer mySerializer = new XmlSerializer(typeof(T));

            StreamWriter myWriter = new StreamWriter(fileName);
            mySerializer.Serialize(myWriter, objectToSerialize);
            myWriter.Close();
        }
        catch (IOException ex)
        {
            Console.WriteLine("IO Exception ", ex.Message);
            return false;
        }
        return true;
    }

Files for inheritance of the dog. There are no xml tags inside the classes.

[XmlRoot(ElementName="Animal")]
public abstract class Animal : IAnimal
{

    /// <summary>
    /// Id of animal
    /// </summary>
    private string id;
    public string ID

........

[XmlRoot(ElementName = "Animals")]
public abstract class Mammal : Animal
{


   public int NumberofTeeth { get; set; }

........

[XmlRoot(ElementName="Dog")]
public class Dog : Mammal
{

    /// <summary>
    /// Constructor - Create an instance of a Dog
    /// </summary>
    public Dog()
    {
    }
........

Who invented Miller columns?

Wikipedia says Miller columns "resemble" something used earlier in Smalltalk and was independently invented by Miller. Who was first - Smalltalk or Miller?

If Smalltalk was first, then who exactly invented Miller columns and why Miller columns are Miller Columns, not X columns, where X is last name of the inventor?

If Miller was first, why Smalltalk is mentioned?

4

1 回答 1

13

如果你想要一个对象列表并将它们序列化为基本类型的列表,那么你需要告诉序列化器什么样的具体类型是可能的。

因此,如果您想将 Dog 和 Cat 对象放入 Animal 列表中,则需要向 Animal 类添加标记,如下所示

[XmlInclude(typeof(Cat))]
[XmlInclude(typeof(Dog))]
[XmlRoot(ElementName="Animal")]
public abstract class Animal : IAnimal
于 2013-10-23T09:15:00.927 回答