C#-不同类型的对象的列表 [英] C# - List of different types of objects

查看:86
本文介绍了C#-不同类型的对象的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个列表,其中包含我的游戏中生成的所有不同单元的所有对象,但它们不是同一类.如果有帮助的话,它们都是主单元类的子类.但是基本上,我有一个具有基本功能的主单元类,然后是剑客,派克曼等的更多内容,我希望能够将所有不同类型放在一个列表中,以便于管理它们.有可能吗?

I want to create a list that contains all the objects for all the different units that are spawned in my game, but they are not all the same class. They all are sub classes of the main unit class if that would help. But basically I have a main unit class with the basic functionality, then more for swordsman, pikeman, etc, and I want to beable to put all different types in one list to be able to manage them easier. Is that possible?

推荐答案

是可以的.

正如罗布(Rob)在他的评论中所说,您需要创建一个List<SharedBaseClass>.

As Rob said in his comment, you need to make a List<SharedBaseClass>.

var someList = new List<SharedBaseClass>();

当您尝试与列表中的特定元素进行交互时,您将需要回退到正确的子类:

When you are trying to interact with a particular element in the List you will need to cast back to the correct sub class:

// throws an exception if type wrong
var someElement = (desiredSubClass) someList[someElementIndex];

// return null if type wrong
var someElement = someList[someElementIndex] as desiredSubClass;

这篇关于C#-不同类型的对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆