3

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") );
}

和错误谈到的哺乳动物:

  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" );
    }
  }
4

1 回答 1

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" );
    }
  }
于 2013-11-10T15:32:43.673 回答