[英]OfType preforms cast instead of filter
Let's say in my database I have 2 classes: Class FooBar and Class BarFoo. 让我们说在我的数据库中我有两个类:Class FooBar和Class BarFoo。 I perform a query on my database which returns class FooBos which contains a list of FooBar BUT the list can contain instances of BarFoo(don't ask me why , this how i got the database and i can't edit it).
我对我的数据库执行查询,返回类FooBos,其中包含一个FooBar列表但该列表可以包含BarFoo的实例(不要问我为什么,这是我如何得到数据库而我无法编辑它)。
Anyway to build my Domain object I do a check to see which class is which using following code 无论如何要构建我的Domain对象,我会检查哪个类使用以下代码
if(FooBos.FooBars.OfType<BarFoo>().Count() != 0)
//Do things for FooBar here
else
//Do Things for BarFoo here
So the problem is after the OfType the entire list is of the Type BarFoo and i can't seem to figure out why. 所以问题是在OfType之后整个列表是Type BarFoo,我似乎无法找出原因。
Anyone knows why this happens ? 谁知道为什么会这样?
Generally, OfType<>
is employed whenever an inheritance relation exists. 通常,只要存在继承关系,就使用
OfType<>
。 In your case, I suspect that FooBar is a child of BarFoo. 在你的情况下,我怀疑FooBar是BarFoo的孩子。
If this is the case then it means all of your objects in the list is either inherit BarFoo or they are just BarFoo objects; 如果是这种情况,则表示列表中的所有对象都是继承BarFoo,或者它们只是BarFoo对象; so
OfType<BarFoo>
returns all objects. 所以
OfType<BarFoo>
返回所有对象。
If you don't mind iterating twice (using Linq), you can use two separate statements: 如果你不介意迭代两次(使用Linq),你可以使用两个单独的语句:
foreach (BarFoo barfoo in FooBos.FooBars.OfType<BarFoo>()
// Do something with barfoo
foreach (FooBar foobar in FooBos.Foobars.OfType<FooBar>()
// Do something with foobar
Otherwise you'll have to do it in a single loop the long way: 否则你将不得不在一个循环中完成它:
foreach (var entry in FooBos.FooBars)
{
BarFoo barfoo = entry as BarFoo;
if (barfoo != null)
{
// Do something with barfoo
}
else
{
FooBar foobar = entry as FooBar;
if (foobar != null)
{
// Do something with foobar
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.