interface IVehicle
{
void DoSth();
}
class VW : IVehicle
{
public virtual void DoSth() { ... }
}
class Golf : VW { }
class Lupo : VW
{
public override void DoSth()
{
base.DoSth();
...
}
}
在我的代码中我有:
List<VW> myCars = new List<VW>();
myCars.Add(new Golf());
myCars.Add(new Lupo());
现在我想评估我是否有车辆 list 。像这样的东西:
if(myCars is List<IVehicle>)
{
foreach(IVehicle v in myCars)
v.DoSth();
}
我该怎么做?通用列表中的 is-operator 不起作用。还有别的办法吗?
最佳答案
即使使用 4.0 差异规则,VW 列表也永远不是 IVehicle 列表,即使 VW 是 IVehicle。方差不是这样运作的。
但是,在 4.0 中,您可以使用:
var vehicles = myCars as IEnumerable<IVehicle>;
if(vehicles != null) {
foreach(var vehicle in vehicles) {...}
}
自 IEnumerable<out T>
表现出协方差。
关于c# - 通用列表上的 is-operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9352723/