[英]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. 我有一些课程,比如Class SubA,SubB和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. 所以我有一个Parent对象数组,其中包含SubA,SubB和SubC的实例。
I am basically trying to loop through the array or Parents and get a particular instance of SubA. 我基本上试图循环遍历数组或父母并获得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: 我建议你使用LINQ的
OfType
方法:
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. 请注意,上面的
a
永远不会为空 - 我假设没关系。
使用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或SingleOrDefault扩展方法。 Single will throw an exception if the collection does not contain a matching element;
如果集合不包含匹配元素,Single将抛出异常; SingleOrDefault will return null.
SingleOrDefault将返回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. 或者您提供允许您识别实例的任何条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.