开发者

Does C# 4's covariance support nesting of generics?

开发者 https://www.devze.com 2022-12-27 21:30 出处:网络
I don\'t understand why \'x\' below converts, but \'y\' and \'z\' do not. var li开发者_如何学Pythonst = new List<List<int>>();

I don't understand why 'x' below converts, but 'y' and 'z' do not.

var li开发者_如何学Pythonst = new List<List<int>>();

IEnumerable<List<int>> x = list;
List<IEnumerable<int>> y = list;
IEnumerable<IEnumerable<int>> z = list;

Does the new covariance feature simply not work on generics of generics or am I doing something wrong? (I'd like to avoid using .Cast<> to make y and z work.)


"z" is fine in C# 4.0, IEnumerable<T> is covariant. List<T> is however not, you cannot make "y" work.

Intuitively, if it were then this would be valid:

List<IEnumerable<int>> y = list
y.Add(new Stack<int>());

Which breaks the promise that "list" can only contain List<int> elements.


You are making several mistakes here. First, covariance and contravariance are not supported for value types, so whatever you try to do with "int" wouldn't work.

Second, the valid example checking for variance in nested generic types looks more like this:

var list = new List<List<String>>();
IEnumerable<IEnumerable<object>> z = list; 

I can assign List of List of strings to IEnumerable of IEnumerables of objects, which is covariance. For more info, check out Covariance and Contravariance FAQ.

0

精彩评论

暂无评论...
验证码 换一张
取 消