[英]How do I call the method of a derived class from a list that contains parent objects?
I am making a game that has an inventory system. 我正在制作具有库存系统的游戏。 The inventory system can contain any WorldObject .
库存系统可以包含任何WorldObject 。 There are a number of derived classes from WorldObject that will be held within the inventory.
WorldObject有许多派生类, 这些类将保存在清单中。
public class WorldObject
{
public virtual void SomeMethod();
}
public class Weapon : WorldObject
{
public override void SomeMethod();
}
public class Tool: WorldObject
{
public override void SomeMethod();
}
and the inventory: 和库存:
public class Inventory
{
public List<WorldObject> ObjectList;
public Inventory()
{
ObjectList = new List<WorldObject>();
}
public void AddToInventory(WorldObject object)
{
ObjectList.Add(object);
}
public void Foo(int itemIndex)
{
Weapon weaponObject = ObjectList[itemIndex] as Weapon;
if(weaponObject != null)
{
weaponObject.SomeMethod();
}
else
{
Tool toolObject = ObjectList[itemIndex] as Tool;
if(toolObject != null)
{
toolObject.SomeMethod();
}
}
}
}
So, is there a better way to call the child methods on each of my items? 因此,是否有更好的方法在我的每个项目上调用子方法? This seems like a lot of headache as my game gets larger.
随着我的游戏越来越大,这似乎让人头疼。 Having 10+ different ways to do the same thing seems wrong.
拥有10多种不同的方式来做同一件事似乎是错误的。
Well, that's why SomeMethod
is virtual, you know? 好吧,这就是为什么
SomeMethod
是虚拟的,您知道吗? So simply: 如此简单:
WorldObject obj = ObjectList[itemIndex];
obj.SomeMethod();
will do what you want — call the override of SomeMethod
in the correct ancestor. 将执行您想要的操作-在正确的祖先中调用
SomeMethod
的替代。
You can read the basics on Wikipedia, for example. 例如,您可以阅读 Wikipedia 的基础知识 。
It's enough to call this method in this way: 以这种方式调用此方法就足够了:
ObjectList[itemIndex].SomeMethod();
And correct your WorldObject class to 并将您的WorldObject类更正为
public class WorldObject
{
public virtual void SomeMethod() {}
}
or 要么
public abstract class WorldObject
{
public abstract void SomeMethod();
}
Since SomeMethod
is virtual, just call it on the object you get from ObjectList[itemIndex]
. 由于
SomeMethod
是虚拟的,因此只需在从ObjectList[itemIndex]
获得的对象上调用它即可。 C# will call the base (no-op) method if the object is just a WorldObject
, or the appropriate override of it if the object is one of the derived classes. 如果对象只是
WorldObject
,则C#将调用base(no-op)方法;如果该对象是派生类之一,则C#将调用该方法的适当替代。 Read about polymorphism on MSDN. 阅读有关MSDN上的多态性的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.