简体   繁体   中英

Accessing an object of a particular sub class from an array of abstract type objects

I have a quick question.

I have a few classes, say Class SubA, SubB and SubC. I also have an abstract class, lets say Parent

So I have an array of Parent objects, which contains instances of SubA, SubB and SubC.

I am basically trying to loop through the array or Parents and get a particular instance of SubA.

I have trieed the following but it produces a type exception:

foreach (SubA a in Parent.GetList())

any help would be greatly appreciated.

Yes, that current code has an implicit cast, which will fail if you've got an object of the "wrong" type in your collection. I suggest you use LINQ's OfType method:

using System.Linq; // Make LINQ extension methods available

...

foreach (SubA a in Parent.GetList().OfType<SubA>())
{
    ...
}

Note that a will never be null in the above - I'm assuming that's okay.

使用OfType<T> 在此处记录

foreach(SubA a in Parent.GetList().OfType<SubA>())

To get a particular instance you can use the Single or SingleOrDefault extension methods on the array. Single will throw an exception if the collection does not contain a matching element; SingleOrDefault will return null.

If you are looking for one object of a certain type

var result = parents.Single(p => p is SubA);

If the objects have a key

var result = parents.Single(p => p is SubA and p.Id == id);

Or you supply whatever criteria allows you to identify the instance.

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