日期:2014-05-18  浏览次数:20984 次

急!!这段代码哪里出错了?为什么张三吃了3次西瓜?
using System;
delegate void eatdelegate(string food);
class Man
{
  private string name;
  public Man(string name)
{
  this.name=name;
}
  public void eat(string food)
  {
  Console.WriteLine(name+"吃"+food);
  }
}
class test
{
  static void eata(string food, params eatdelegate[] values)
  {
  if (values == null)
  {
  Console.WriteLine("没有人想吃东西了");
  }
  else
  {
  eatdelegate eatchain = null;
  foreach (eatdelegate i in values)
  {
  eatchain += i;
  eatchain(food);
  }

  }
  }
  static void Main()
  {

  Man zs = new Man("张三");
  Man ls = new Man("李四");
  Man ww = new Man("王五");
  eatdelegate zseat = new eatdelegate(zs.eat);
  eatdelegate lseat = new eatdelegate(ls.eat);
  eatdelegate wweat = new eatdelegate(ww.eat);
  eata("西瓜", zseat, lseat, wweat);
  eata("橘子", lseat);
  }
}


------解决方案--------------------
C# code
                eatdelegate eatchain = null;
                foreach (eatdelegate i in values)
                {
                    eatchain += i;
                    //eatchain(food);这里去掉
                }
                eatchain(food);//写到这里

------解决方案--------------------
foreach (eatdelegate i in values)
{
// eatchain += i;
i(food);
}

呵呵,同楼上,还有这样吃的