2012-05-23 42 views
1

我有一个静态列表:收藏列表有多种类型的用户定义对象?

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

名单摄入量是两个不同类型的对象(机)的:

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

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

+8

“我怎么知道,如果该项目是AC型或发电机型的?”你不是。通过“IMachines”接口来引用对象,你只是说只有那个接口指定的东西才是你关心的东西。有办法解决它,但正确的答案通常是解决设计问题,需要你做到这一点。 – Telastyn

+1

有不同的方法来做到这一点。 ''''作为'运营商,也是我的答案中所描述的。但Telastyn就在这里。您应该修复设计问题并将所需的一切通过界面公开。 –

+0

我应该使用类引用变量而不是接口? ... –

回答

2

使用“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 
    } 
} 
5

可以使用is operator

检查如果一个对象是与给定类型

例如兼容:

if(item is AC) 
{ 
    // it is AC 
} 
+2

请注意,如果您随后想将'item'视为'AC',那么您可以使用'as'运算符并检查null,在此时您可以使用键入的'AC'。 –

1

也可以使用OfType()方法仅返回指定类型的物品:

IEnumerable<Generator> generators = mList.OfType<Generator>(); 
3
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()); 
     } 

    } 
0

使用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!!!"); 
      } 

     } 
+0

作为与is组合使用的操作符是没有意义的。如果您决定使用'is',则直接转换为匹配类型不会抛出异常。 这里最好的解决方案是使用'as'运算符并检查null。 –

+0

如果机器是Generator,机器**不能为null,因为null对象没有类型。所以周围的“if”已经过时了。 – fero

+0

@MichalB。我只是同意。此代码仅供说明。 – Mzn

0

如果您想根据类型做不同的操作,您可以使用GroupBytype

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

以下是代码片段

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 {}