集合列表,具有多种类型的用户定义对象

本文关键字:类型 用户 定义 对象 种类 列表 集合 | 更新日期: 2023-09-27 18:35:01

我有一个静态列表:

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

该列表中包含两种不同类型的对象(机器(:

IMachines machine = new AC();
IMachines machine = new Generator();

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

集合列表,具有多种类型的用户定义对象

您可以使用

is运算符:

检查对象是否与给定类型兼容

例如:

if(item is AC)
{
  // it is AC
}
    interface IVehicle {
    }
    class Car : IVehicle
    {
    }
    class Bicycle : IVehicle
    {
    }
    static void Main(string[] args)
    {
        var v1 = new Car();
        var v2 = new Bicycle();
        var list = new List<IVehicle>();
        list.Add(v1);
        list.Add(v2);
        foreach (var v in list)
        {
            Console.WriteLine(v.GetType());
        }
    }

使用 "is" 运算符。

List<IMachines> list = new List<IMachines>();
list.Add(new AC());
list.Add(new Generator());
foreach(IMachines o in list)
{
  if (o is Ingredient)
  {
    //do sth
  }
  else if (o is Drink)
  {
    //do sth
  }
}

还可以使用 OfType() 方法仅返回指定类型的项:

IEnumerable<Generator> generators = mList.OfType<Generator>();

使用isas运算符。

        List<IMachines> mList =new List<IMachines>();
        IMachines machine = mList.Where(x => x.Name == "MachineName").FirstOrDefault();
        if (machine != null)
        {
            if (machine is Generator)
            {
                Generator generator = machine as Generator;
                //do something with generator
            }
            else if (machine is AC)
            {
                AC ac = machine as AC;
                //do something with ac
            }
            else
            {
                //do you other kinds? if no, this is never going to happen
                throw new Exception("Unsupported machine type!!!");
            }
        }

如果要根据类型进行不同的操作,可以使用GroupBy type

通过这样做,您可以获取与每个派生类型对应的子列表。

以下是代码片段

    void Main()
    {
        List<IMachines> mList = new List<IMachines>();
        mList.Add(new AC());
        mList.Add(new Generator());
        mList.Add(new AC());
        mList.Add(new Generator());
        mList.Add(new Generator());
        mList.Add(new Generator());
        var differentIMachines = mList.GroupBy(t=>t.GetType());
        foreach(var grouping in differentIMachines)
        {
                Console.WriteLine("Type - {0}, Count - {1}", grouping.Key, grouping.Count());
                foreach(var item in grouping)
                {
                //iterate each item for particular type here
                }
        }
    }
    interface IMachines {   }
    class AC : IMachines {}
    class Generator : IMachines {}