简体   繁体   English

如何在 C# 中拥有多个派生类型的单个数据集合?

[英]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类,称为BlueCardRedCard 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需要包含BlueCardRedCard的单个数组。 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.

相关问题 C#单个集合中的多个泛型类型 - C# Multiple generic types in single collection 多个派生类的C#单类收集方法 - C# Single Generic Collection Method for Multiple Derived Classes 我可以从Dapper查询返回多个派生类型的集合 - Can I return a collection of multiple Derived Types from Dapper query 如何在C#的集合中保存不同类型的对象? - How can I hold objects of different types in a collection in c#? 我有一个单一文件,需要随机序列化多个对象。我怎么能在c#中? - I have a Single File And need to serialize multiple objects randomly. How can I in c#? 如何使派生类具有所有基本数据类型属性都为Nullable类型的强制性? - How can I make mandatory for a derived class to have all basic data-type properties to be of Nullable types? 我可以在C#中使用Untyped Collection吗? - Can I have a Untyped Collection in C# 如何在单个 mrt 文件中的不同页面上拥有多个业务对象并在 C# WinForm 中显示它 - How can I have multiple Business Objects on different pages in a single mrt file and display it in C# WinForm 如何在C#中创建列表集合并为其初始化数据 - How can I Create a Collection of Lists in C# and initialize data to it C#在单个端口上传输多种数据类型(接收) - C# Transferring multiple data types over a single port (receiving)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM