传递一个接口集合 [英] Passing an Interface collection
问题描述
假设你有下面的类:
类车:IPainting
{
...
}
那么这样的功能:
无效AddCars(IEnumerable的<汽车>收集)
然后,代码片段是这样的:
汽车宝马=新车();
乘坐的奔驰车=新车();
IPainting一个=(IPainting)宝马;
IPainting B =(IPainting)奔驰;
IPainting [] =绘画新IPainting [] {A,B};
AddCars(画); //编译失败
这当然不能编译,因为AddCars()方法只接受汽车集合,但它是个什么'画'阵列是由
我知道C#4.0可能会提供一个解决方案。有任何解决方法今天呢?
谢谢,
阿尔贝托
< DIV CLASS =h2_lin>解决方案
C#4不会让你写的代码,因为该方法 AddCars
预计的的IEnumerable<汽车>
它实现了 IPainting
。这并不意味着你可以通过的任何的类实现 IPainting
(你可以比如有一个类自行车:IPainting
是无关的车
类任何然而,它将使其他方式;如果你有无效AddCars(IEnumerable的< IPainting>集合)
你可以传递一个列表<租车方式>
的方法
在那之前,你需要坚持通过车
序列的方法,通过使用一些铸造的机制(如绘画。铸造<租车方式>()
其他答案建议)
Suppose you have the following class:
class Car : IPainting
{
...
}
Then a function like this:
void AddCars(IEnumerable<Car> collection)
Then a code snippet like this:
Car bmw = new Car();
Car mercedes = new Car();
IPainting a = (IPainting) bmw;
IPainting b = (IPainting) mercedes;
IPainting[] paintings = new IPainting[] {a, b};
AddCars(paintings); // fails to compile
This of course doesn't compile because the AddCars() method accepts only a collection of Cars but it is what the 'paintings' array is made of.
I know that C# 4.0 will probably provide a solution for this. Is there any workaround today for it?
Thanks,
Alberto
C# 4 will not allow the code that you wrote, since the method AddCars
expects an IEnumerable<Car>
which implements IPainting
. This does not mean that you can pass any class implementing IPainting
(you could for instance have a class Bike : IPainting
that has nothing to do with the Car
class whatsoever. However, it will allow the other way around; if you have void AddCars(IEnumerable<IPainting> collection)
you can pass a List<Car>
to the method.
Until then, you will need to stick to passing Car
sequences to the method, by using some casting mechanism (such as painting.Cast<Car>()
suggested in other answers).
这篇关于传递一个接口集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!