我正在学习编程,我不得不创建一个蛇游戏.
在游戏中,蛇有大约5种可能的消耗品,我决定把每个新的都Consumable放在一个Consumable阵列中.
现在我想foreach通过数组循环迭代并执行以下操作:
foreach (Apple apple in consumables)
{
renderer.DrawApple(apple);
}
Run Code Online (Sandbox Code Playgroud)
但是当数组中有不同的对象时,如a Apple和a SegmentRemover(这是可能的,因为它们从Consumable类中继承),那么编译器SegmentRemover也会迭代,我得到一个无效的强制转换异常.
我想,因为我在foreach循环中声明我只想迭代Apple对象,它应该工作.
有没有简单的方法来解决这个问题?最好不要使用var或者typeof,因为我还不允许使用这些.
所以我希望能够创建一个标题并用例如"="加下划线.但是我希望"="的数量与标题中的字符数相匹配.我希望能够用for循环来完成它.
这是我到目前为止所拥有的.
string headLine = "Example";
Console.WriteLine(headLine);
for (char i = '='; i <= headLine.Length; i += '=')
{
Console.WriteLine(i);
}
Run Code Online (Sandbox Code Playgroud)