我正在从一本书中学习 C#,并且我正在扩展一个示例以更好地理解语法。
我正在尝试使用以下代码循环遍历对象集合并仅挑选某些对象,以便将它们加载到单独的数组中。我现在正在为这条特定的线路苦苦挣扎:
if (animalCollection[i].Equals(Chicken))
这是 Program.cs 的完整代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch11Ex02
{
class Program
{
static void Main(string[] args)
{
Animals animalCollection = new Animals();
animalCollection.Add(new Cow("Jack"));
animalCollection.Add(new Chicken("Vera"));
animalCollection.Add(new Chicken("Sally"));
Animal[] birds = new Animal[2];
for (int i = 0; i < animalCollection.Count; i++)
{
if (animalCollection[i].Equals(Chicken))
birds[i] = animalCollection[i];
}
foreach (Animal myAnimal in animalCollection)
{
myAnimal.Feed();
}
Console.ReadKey();
}
}
}
我的目标是仅将对象类型 Chicken 加载到一个名为 bird 的新数组中。
这是动物类的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch11Ex02
{
public abstract class Animal
{
protected string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public Animal()
{
name = "The animal with no name";
}
public Animal(string newName)
{
name = newName;
}
public void Feed()
{
Console.WriteLine("{0} has been fed." , name);
}
internal bool equals()
{
throw new NotImplementedException();
}
}
}
这是鸡类的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch11Ex02
{
public class Chicken : Animal
{
public void LayEgg()
{
Console.WriteLine("{0} has laid an egg." , name);
}
public Chicken(string newName): base(newName)
{
}
}
}
这是动物类的代码:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch11Ex02
{
public class Animals : CollectionBase
{
public void Add(Animal newAnimal)
{
List.Add(newAnimal);
}
public void Remove(Animal newAnimal)
{
List.Remove(newAnimal);
}
public Animals()
{
}
public Animal this[int animalIndex]
{
get
{
return (Animal)List[animalIndex];
}
set
{
List[animalIndex] = value;
}
}
}
}