序列化List <t>错误反映字段</t>

时间:2013-11-10 15:16:39

标签: c# xml serialization

xml序列化新手,无法找到我的具体问题。

使用此代码序列化:

Human h = new Human();

XmlSerializer writer = new XmlSerializer( typeof( Human ) );

System.IO.StreamWriter file = new System.IO.StreamWriter(
  @"c:\temp\serializerExample.xml" );
writer.Serialize( file, h );
file.Close();

获取内部异常:

  

{“反映字段'_foods'时出错。”}

人:

public class Human : Mammal
{
public string Name
{
  get
  {
    return "Bob";
  }
}
public Human()
{
  this.AddFood( new Hamburger("Name") );
  this.AddFood( new Salad("Name") );
}

和Mammal所说的错误:

  public abstract class Mammal
  {
    public List<Food> _foods = new List<Food>();

    protected void AddFood(Food food)
    {
      _foods.Add( food );
    }

    public void Eat()
    {
      foreach ( var food in _foods )
      {
        food.Eat();
      }
    }
  }

食物:

  [XmlRoot(Namespace="Food")]
  [XmlInclude(typeof(Hamburger))]
  [XmlInclude( typeof( Salad ) )]
  public abstract class Food
  {
    public string PropertyName
    {
      get;
      set;
    }
    public abstract int Calories
    {
      get;
    }
    public abstract void Eat();
    public Food()
    {
    }
    public Food( string propertyName )
    {
      PropertyName = propertyName + " food ";
    }
  }

汉堡包:

public class Hamburger : Food
  {
    public Hamburger()
    {
    }
    public Hamburger(string propertyName) :base(propertyName)
    {

    }
    public override int Calories
    {
      get
      {
        return 500;
      }
    }

    public override void Eat()
    {
      Console.WriteLine( "Eat Hamburgers" );
    }
  }

沙拉:

  public class Salad : Food
  {
    public Salad(string propertyName) : base(propertyName)
    {

    }
    public override int Calories
    {
      get
      {
        return 200;
      }
    }

    public override void Eat()
    {
      Console.WriteLine( "Eat Salad" );
    }
  }

1 个答案:

答案 0 :(得分:3)

我认为Salad缺少Default(无参数)构造函数

public class Salad : Food
  {
    public Salad (){}

    public Salad(string propertyName) : base(propertyName)
    {

    }
    public override int Calories
    {
      get
      {
        return 200;
      }
    }

    public override void Eat()
    {
      Console.WriteLine( "Eat Salad" );
    }
  }