转换List <keyvaluepair <,>&gt;时出错到IEnumerable <object>

时间:2017-07-27 07:19:19

标签: c# generics casting ienumerable covariance

为什么我能够这样做:

IEnumerable<object> objs;
List<Student> students = new List<Student>();
objs = students;

但不是这样:

IEnumerable<object> objs2;
List<KeyValuePair<int, string>> kvs = new List<KeyValuePair<int, string>>
{
    new KeyValuePair<int, string>(1, "ab"),
    new KeyValuePair<int, string>(2, "xy")
};
objs2 = kvs; //error

抛出的错误:

>     Cannot implicitly convert type
> 'System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<int,
> string>>' to 'System.Collections.Generic.IEnumerable<object>'. An
> explicit conversion exists (are you missing a cast?)

重复问题中接受的答案是KeyValuePair是一个结构,尽管这种转换没有任何错误:

KeyValuePair<int, string> kv = new KeyValuePair<int, string>();
object oj = kv;

所以我假设缺少协方差和逆变的一些事情!

0 个答案:

没有答案