简体   繁体   中英

foreach inherited (sub-class) object in a super-class list

I have a super-class named "ClassA" and two sub-classes "Class1" and "Class2".

I have a list containing objects of "Class1" and "Class2", that list is of type "ClassA".
I want to loop through only the "Class1" objects in the list by doing something like

List<ClassA> AList = new List<ClassA>;
AList.Add(new Class1());
AList.Add(new Class2());

foreach (Class1 c1 in AList)
{
    // Do Something
}

but when I do that, the code throws an exception when it reaches an object that is not of type "Class1".

How can this be done in a simple way without having to check the type of the object in the list and cast it if it's the correct type. like this:

foreach (ClassA cA in AList)
{
    if (cA.GetType() == typeof(Class1))
    {
        // Do Something
    }
}

Using LINQ:

foreach (Class1 c1 in AList.OfType<Class1>()) { }

Note that if you want to check for a type in a loop, the as and is operators are meant for this. Like:

foreach (ClassA cA in AList) {
  Class1 c1 = cA as Class1;
  if (c1 != null) {
    // do something
  }
}
foreach(Class1 c1 in AList.OfType<Class1>())
{
    //do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM