集合中的元素不能强制类型转换???急!

sunrise10 2003-12-12 11:31:16
Cow类,Chicken类,继承类Animal

Animal[] animalArray=new Animal[2];
Cow myCow1=new Cow("Deirdre");
animalArray[0]=myCow1;
animalArray[1]= new Chicken("Ken");
foreach(Animal myAnimal in animalArray)
{
Console.WriteLine("New{0} object added to Array collection," +
"Name={1}",myAnimal.ToString(),myAnimal.Name);
}
数组中转换成功

ArrayList animalArrayList=new ArrayList();
Cow myCow2=new Cow("Hayley");
animalArrayList.Add("myCow2");
animalArrayList.Add(new Chicken("Roy"));
foreach(Animal myAnimal in animalArrayList)
{
Console.WriteLine("New{0} object added to Array collection," +
"Name={1}",myAnimal.ToString(),myAnimal.Name);
}
集合中出现类型转换不成功错误
...全文
73 4 打赏 收藏 举报
写回复
4 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
sunrise10 2003-12-12
嘿嘿,谢了
  • 打赏
  • 举报
回复
brightheroes 2003-12-12
这是个笔误,呵呵
楼主的方法是没有任何问题的^_^
  • 打赏
  • 举报
回复
brightheroes 2003-12-12
see here

animalArrayList.Add("myCow2"); --- add a string into arraylist
animalArrayList.Add(new Chicken("Roy")); --- and a chicken into arraylist

---->

animalArrayList.Add(myCow2); --- add a cow into arraylist
animalArrayList.Add(new Chicken("Roy"));

that is ok
  • 打赏
  • 举报
回复
FileNewExit 2003-12-12
try :

foreach(object ob in animalArrayList)
{
Animal myAnilmal = (Animal)ob;
Console.WriteLine("New{0} object added to Array collection," +
"Name={1}",myAnimal.ToString(),myAnimal.Name);
}
  • 打赏
  • 举报
回复
相关推荐
发帖
C#
加入

10.7w+

社区成员

.NET技术 C#
申请成为版主
帖子事件
创建了帖子
2003-12-12 11:31
社区公告

让您成为最强悍的C#开发者