将nullables列表转换为对象列表

dan*_*nze 2 c#

为什么第二次转换失败了

InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[System.Nullable`1[System.Boolean]]' to type 'System.Collections.Generic.IEnumerable`1[System.Object]'.
object list1 = new List<string>() { "a", "b" };
object list2 = new List<bool?>() { true, false };

IEnumerable<object> bind1 = (IEnumerable<object>)list1;
IEnumerable<object> bind2 = (IEnumerable<object>)list2;
Run Code Online (Sandbox Code Playgroud)

任何想法,将不胜感激.

Jon*_*eet 6

Nullable<T>是一种值类型,并且通用协方差不适用于值类型(因此,例如,没有转换IEnumerable<int>IEnumerable<object>任何一种):

差异仅适用于参考类型; 如果为变量类型参数指定值类型,则该类型参数对于生成的构造类型是不变的.

最简单的解决方法是使用Cast:

IEnumerable<object> bind2 = list2.Cast<object>();
Run Code Online (Sandbox Code Playgroud)