【发布时间】:2017-06-10 17:27:33
【问题描述】:
我完全不熟悉 c# 和编程。 我的任务是创建一个类“动物”,它是“捕食者”和“草食性”的父类,这两个类分别是“狼”、“狐狸”、“野兔”、“鹿”的父类。所以我就这么做了。下一步是创建这些对象的数组,并计算数组中有多少食肉动物和食草动物。这就是问题发生的地方。 (类的功能可以是任意的)
我的课:
public abstract class Animal
{
}
public abstract class Predator : Animal
{
protected string predatorName;
public Predator (string typeOfAnimal)
{
this.predatorName = typeOfAnimal;
}
}
public abstract class Herbivorous : Animal
{
protected string herbivorousName;
public Herbivorous (string typeOfAnimal)
{
this.herbivorousName = typeOfAnimal;
}
}
public class Wolf : Predator
{
protected string wolfName;
public Wolf (string typeOfAnimal, string nameOfTheWolf) : base(typeOfAnimal)
{
this.wolfName = nameOfTheWolf;
}
}
public class Fox : Predator
{
protected string foxName;
public Fox(string typeOfAnimal, string nameOfTheFox) : base(typeOfAnimal)
{
this.foxName = nameOfTheFox;
}
}
public class Hare : Herbivorous
{
protected string hareName;
public Hare(string typeOfAnimal, string nameOfTheHare) : base(typeOfAnimal)
{
this.hareName = nameOfTheHare;
}
}
public class Deer : Herbivorous
{
protected string deerName;
public Deer(string typeOfAnimal, string nameOfTheDeer) : base(typeOfAnimal)
{
this.deerName = nameOfTheDeer;
}
}
我的主要:
class Program
{
static void Main(string[] args)
{
Problem2.Wolf wolf1 = new Problem2.Wolf("Predator", "Ghost");
Problem2.Wolf wolf2 = new Problem2.Wolf("Predator", "Nymeria");
Problem2.Wolf wolf3 = new Problem2.Wolf("Predator", "Grey Wind");
Problem2.Fox fox1 = new Problem2.Fox("Predator", "Eevee");
Problem2.Fox fox2 = new Problem2.Fox("Predator", "Vulpix");
Problem2.Hare hare1 = new Problem2.Hare("Herbivorous", "Bugs Bunny");
Problem2.Hare hare2 = new Problem2.Hare("Herbivorous", "Easter Bunny");
Problem2.Deer deer1 = new Problem2.Deer("Herbivorous", "Bambi");
Problem2.Deer deer2 = new Problem2.Deer("Herbivorous", "Faline");
Problem2.Deer deer3 = new Problem2.Deer("Herbivorous", "Sven");
Problem2.Deer deer4 = new Problem2.Deer("Herbivorous", "Mena");
Problem2.Animal[] arrayOfAnimals = new Problem2.Animal[] {wolf1, wolf2, wolf3, fox1, fox2, deer1, deer2, deer3, deer4, hare1, hare2};
for (int i = 0; i < arrayOfAnimals.Length; i++)
{
int counter = 0;
bool check = false;
Problem2.Herbivorous myHerbivorousAnimal = arrayOfAnimals[i];
check = myHerbivorousAnimal is Problem2.Herbivorous;
if (check == true)
{
counter++;
}
}
}
}`
我有一个编译问题:
错误 CS0266 无法将类型“Problem2.Animal”隐式转换为 '问题2.草食性'。存在显式转换(您是否缺少 演员表?)
所以出了什么问题?或者有没有正确的方法来计算我的“动物”数组中的“捕食者”和“草食性”? 谢了
【问题讨论】:
-
你可以这样做
arrayOfAnimals.OfType<Problem2.Herbivorous>().Count();。这是一个非常简单的方法。这仅取决于您是在学习使用基础知识进行编码,还是想要以最有效的方式表达您的需求。 -
另一项任务是使该计数器与“is”或“as”一起工作。所以过了一会儿我像这样重写了我的代码
var herbivirousCounter = allAnimals.Where(x => x is Problem2.Herbivorous).ToList();
标签: c#