简体   繁体   English

通用列表上的is-operator

[英]is-operator on generic list

interface IVehicle 
{
    void DoSth();
}

class VW : IVehicle
{
    public virtual void DoSth() { ... }
}

class Golf : VW { }

class Lupo : VW
{
    public override void DoSth()
    {
        base.DoSth();
        ...
    }  
}

in my code i have: 在我的代码我有:

List<VW> myCars = new List<VW>();
myCars.Add(new Golf());
myCars.Add(new Lupo());

now i want to evaluate if i have a list of vehicles. 现在我想评估我是否有车辆清单。 something like: 就像是:

if(myCars is List<IVehicle>)
{
    foreach(IVehicle v in myCars)
        v.DoSth();
}

how can i do this? 我怎样才能做到这一点? the is-operator on the generic list does not work. 通用列表中的is-operator不起作用。 is there another way? 有另一种方式吗?

Even with 4.0 variance rules, a list-of-VW is not ever a list-of-IVehicle, even if a VW is an IVehicle. 即使使用4.0方差规则,即使VW是IVehicle,大众列表也不会是IVehicle列表。 That isn't how variance works. 这不是方差的工作原理。

However, in 4.0, you could use: 但是,在4.0中,您可以使用:

var vehicles = myCars as IEnumerable<IVehicle>;
if(vehicles != null) {
     foreach(var vehicle in vehicles) {...}
}

Since IEnumerable<out T> exhibits covariance. 因为IEnumerable<out T>表现出协方差。

In .net 4 it is posible using generic parameter variance. 在.net 4中,它可以使用通用参数方差。 Read more about it here 在这里阅读更多相关信息

You could do this: 你可以这样做:

if (typeof(IVehicle).IsAssignableFrom(myCars.GetType().GetGenericArguments[0]))
    foreach (IVehicle v in myCars)
        //...

This assumes that you know myCars is a generic type. 这假设您知道myCars是通用类型。 If you don't know that for sure, you would need to do an additional check or two first. 如果您不确定,那么您需要先进行一两次检查。

However, since you aren't using any member of list other than GetEnumerator, you can do this: 但是,由于您没有使用GetEnumerator以外的任何列表成员,因此您可以这样做:

if (myCars is IEnumerable<IVehicle>) //...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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