c# - 如何确定数组中唯一派生类型的数量?

标签 c# .net arrays linq

我有以下类(class)

客户

abstract class Customer
{
    public int id;
    public string name;
    public double balance;
}

NormalCustomer

class NormalCustomer: Customer
{
}

SubscriberCustomer

class SubscriberCustomer:Customer
{
    public int LandMinutes;
    public int MobileMinutes;
}

如果我们创建一个 Customers 数组

Customer[] customers = new Customer[100];
customers[0]=new NormalCustomer();
customers[1] = new NormalCustomer();
customers[2] = new SubscriberCustomer();
customers[3] = new NormalCustomer();
customers[4] = new SubscriberCustomer(); 

问题是我如何知道数组中有多少对象是 NormalCustomers 以及数组中有多少对象是 SubscriberCustomers

最佳答案

您可以使用 OfType扩展方法

customers.OfType<NormalCustomer>().Count() 

您需要使用 using 指令导入 System.Linq 命名空间:

using System.Linq;

关于c# - 如何确定数组中唯一派生类型的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38038865/

相关文章:

c# - 解压带有子目录的文件

c# - 构造函数定义中的这个冒号叫什么?

.net - 集合论和.NET

c# - Azure DocumentClient 线程安全

c# - 如何让零钱计算器更简单

c# - 在 C# 应用程序中处理多个表单

c++ - 遗留代码似乎有溢出,但我不确定

c - 将数组传递给 void 函数

arrays - 如何在多维复数数组的特定维度内进行洗牌

c# - 在第一个空格处拆分字符串