Interface Collection Transfer

Suppose you have the following class:

class Car : IPainting
{
 ...
}

Then such a function:

void AddCars(IEnumerable<Car> collection)

Then the code snippet looks 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, does not compile, because the AddCars () method only accepts the Cars collection, but this is what the array of "pictures" is made of.

I know that C # 4.0 is likely to provide you with a solution. Is there any workaround today?

Thanks,

Alberto

+5
source share
4 answers

# 4 , AddCars IEnumerable<Car>, IPainting. , , IPainting (, class Bike : IPainting, Car, ; void AddCars(IEnumerable<IPainting> collection) List<Car> .

Car , - (, painting.Cast<Car>(), ).

+3

:

void AddCars<T>(IEnumerable<T> collection) where T : IPainting
+7

Linq: AddCars(paintings.Cast<Car>());

+4

. , IPainting, , IPainting .

, , , .

AddCars(new Car[] { bmw, mercedes });
+4
source

All Articles