[英]How can I have a single data collection of multiple derived types in C#?
I'm not sure if I phrased my question appropriately, but consider the following scenario:我不确定我是否恰当地表达了我的问题,但请考虑以下情况:
I have an abstract class called Card
.我有一个名为Card
的抽象类。 The Card
class contains many members. Card
类包含许多成员。 I have two classes that derive from Card
called BlueCard
and RedCard
.我有两个派生自Card
类,称为BlueCard
和RedCard
。 To visualize this:为了形象化:
public abstract class Card{
//many members
}
public class BlueCard : Card{
//many members
}
public class RedCard : Card{
//many members
}
Now, suppose I have a class Deck
.现在,假设我有一个类Deck
。 Deck
needs to contain a single array of both BlueCard
and RedCard
. Deck
需要包含BlueCard
和RedCard
的单个数组。 Is there a way to go about this?有没有办法解决这个问题?
I'm using this approach in a similar situation myself, where an ElementGroup object contains a collection of objects that are either of type Element or of a type deriving from Element.我自己在类似的情况下使用这种方法,其中 ElementGroup 对象包含一组对象,这些对象要么是 Element 类型,要么是从 Element 派生的类型。 I think something like this should suit your case:我认为这样的事情应该适合你的情况:
public class Deck {
public Deck() {
_cardArray = new Card[52];
}
private Card[] _cardArray;
public void DrawCard(int cardNumber) {
var card = _cardArray[cardNumber];
if (card.GetType() == typeof(Card)) {
// Do something
}
else if (card.GetType() == typeof(BlueCard)) {
// Do something
}
else if (card.GetType() == typeof(RedCard)) {
// Do something
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.