[英]How to access different types of classes in a single object array in C#
I have an object array that is supposed to hold objects of different classes. 我有一个对象数组,应该保存不同类的对象。 I need to write down the attributes of those classes but don't know how to access them.
我需要写下这些类的属性,但不知道如何访问它们。
For example: 例如:
object[] NationalTeam;
possibly holding: 可能持有:
class Swimmer
class Runner
etc. 等等
with different attributes. 具有不同的属性。 Can't access them with
NationalTeam[i]
. 无法使用
NationalTeam[i]
访问它们。 Can it be done with overloading [] indexer? 可以使用重载[]索引器吗? If yes, how?
如果是,怎么办?
You will have to either: 您将必须:
Cast them: 投放他们:
object teamMember = NationalTeam[0]; if (teamMember is Swimmer) { Swimmer swimmerTeamMember = (Swimmer)teamMember; // Work with swimmer } // ... and so on
Add and implement an interface or base class such as ITeamMember
or TeamMember
. 添加并实现接口或基类,例如
ITeamMember
或TeamMember
。
interface ITeamMember { /* common properties */ } class Swimmer : ITeamMember { /* ... */ } ITeamMember[] NationalTeam;
Or use a combination of both. 或同时使用两者。
Eric Lippert (one of the designers of C#) has a fantastic walk through to explain a very similar problem. 埃里克·利珀特(C#的设计师之一)有一个很棒的演练来解释一个非常相似的问题。 I suggest that you read it.
我建议您阅读。 http://ericlippert.com/2015/04/27/wizards-and-warriors-part-one/
http://ericlippert.com/2015/04/27/wizards-and-warriors-part-one/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.