Skip to main content
 首页 » 编程设计

c#之集合列表具有不止一种类型的用户定义对象

2024年01月16日41freeliver54

我有一个静态列表:

public static List<IMachines>mList =new List<IMachines>(); 

该列表包含两种不同类型的对象(机器):
IMachines machine = new AC(); 
IMachines machine = new Generator(); 

如果在将项目添加到列表后,我想通过其名称属性搜索特定机器,然后在使用 foreach 循环进行遍历之后,如果在列表中找到该项目......我应该如何知道该项目是否为 AC类型还是 Generator 类型?

请您参考如下方法:

您可以使用 is operator :

Checks if an object is compatible with a given type



例如:
if(item is AC) 
{ 
  // it is AC 
}