Failed to get the received list <>

I have

class A
{}

class B : A
{}

I also have a method that expects List parameter

void AMethod(List<A> parameter)
{}

Why i can't

List<B> bs = new List<B>();
AMethod(bs);

And secondly, what is the most elegant way to do this job?

considers

+3
source share
4 answers

You can make a general attribute of a method as follows:

void AMethod<T>(List<T> parameter) where T : A
{}

Or you can wait for .NET 4 where this script is supported for IEnumerable <>

+5
source

Unlike other answers, this is not supported in .NET 4.0. Only interfaces and delegates support common variance. However, .NET 4.0 will allow you to do this:

void AMethod(IEnumerable<A> parameter) {}
...
List<B> list = new List<B>();
AMethod(list);

.NET 3.5 Cast:

void AMethod(IEnumerable<A> parameter) {}
...
List<B> list = new List<B>();
AMethod(list.Cast<A>());

AMethod generic:

void AMethod<T>(List<T> parameter) where T : A
...
List<B> list = new List<B>();
AMethod(list); // Implicitly AMethod<B>(list);

, - , AMethod. A, - . , .

+7

. ( # 4.0).

+4

Source: https://habr.com/ru/post/1736450/


All Articles