检查特定列表索引处的子类
您好,我想知道如何检查列表中特定位置的对象是否等于某个对象。
我有 3 个“Ship”子类,它们被称为“Enemy”、“Enemy2”、“Player” 所有这些都保存在我称之为“船舶”的列表中,
我想知道您如何在列表中检查索引处的项目是否属于上述项目之一。这很难解释,我会尝试用代码来解释。
for (int i = 0; i < Game1.Ships.Count; i++)
{
if(Game1.Ships.ElementAt(i) == "Enemy")
Enemy e = Game1.Ships.ElementAt(i);
if (this.collisionBox.Intersects(e.collisionBox))
{
e.Destroy(false);
//Execute Destory(bool).
}
}
else
i++;
//Skip to next item.
这大致就是我想要做的,显然我需要检查它是否不是玩家。我还必须对 Enemy2 执行相同的循环。 请注意,虽然“Ship”默认情况下没有 Destroy(bool),但它只存在于“Enemy”和“Enemy”上。 “敌人2”。
Hi I'm wondering how you would check if an object at a specific location in a List is equal to something.
I have 3 subclasses of "Ship", they are called "Enemy", "Enemy2", "Player"
All of them are saved in a List that I call "Ships"
I'm wondering how you would check in a list that the item at index is of one of the above. It's pretty hard to explain, I'll try to explain in code.
for (int i = 0; i < Game1.Ships.Count; i++)
{
if(Game1.Ships.ElementAt(i) == "Enemy")
Enemy e = Game1.Ships.ElementAt(i);
if (this.collisionBox.Intersects(e.collisionBox))
{
e.Destroy(false);
//Execute Destory(bool).
}
}
else
i++;
//Skip to next item.
That is roughly what I'm trying to do, obviously I'd need to check that It's not a Player. And I'd also have to do the same loop for Enemy2.
Observe though that "Ship" does not have a Destroy(bool) by default, it's only exsists on "Enemy" & "Enemy2".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需使用
is
:just use
is
:您绝对不想像这样使用 ElementAt() ,因为它每次都会遍历序列的开头。我建议使用
foreach
循环和OfType<>()
来代替:或者,如果
Game1.Ships
实现ICollection
code>,您可以使用for
循环并将.ElementAt(i)
替换为[i]
:You absolutely do not want to use
ElementAt()
like this, as it iterates over the start of the sequence every time. I would suggest using aforeach
loop andOfType<>()
instead:Or, if
Game1.Ships
implementsICollection
, you could use yourfor
loop and replace.ElementAt(i)
with[i]
:并考虑
这似乎是一个不错的策略
我不能/不会添加界面以方便选择船舶类型,那么您可以求助于
我需要指出哪种方法会获得我的投票吗?
and consider
This would seem to be a nice strategy seeing that
I you cannot/will not add the interface to make it easy to select the ship types then you could resort to
Do I need to point out which method would have my vote ?
或者 LINQish:
如果您想摆脱 ToList() 转换,请定义以下扩展方法
并像这样使用它:
Or LINQish:
If you want to get rid of the ToList() conversion, define the following extension method
And use it like this: