Почему ковариация не работает с универсальным методомC#

Место общения программистов C#
Гость
Почему ковариация не работает с универсальным методом

Сообщение Гость »


Assume I have interface and class:

Код: Выделить всё

public interface ITree {} public class Tree : ITree {} 
As

Код: Выделить всё

IEnumerable
is covariant, the code line below is compiled successfully:

Код: Выделить всё

IEnumerable trees = new List(); 
But when I put it into generic method:

Код: Выделить всё

public void Do() where T : ITree {      IEnumerable trees = new List(); } 
I get compiled error from compiler:

Error 1 Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?) D:\lab\Lab.General\Lab.General\Program.cs 83 40 Lab.General

Why covariance does not work in this case?


Источник: https://stackoverflow.com/questions/127 ... ric-method

Вернуться в «C#»