gpt4 book ai didi

c# - 将可空值列表转换为对象列表

转载 作者:行者123 更新时间:2023-11-30 19:27:49 25 4
gpt4 key购买 nike

为什么第二次转换失败

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;

如有任何想法,我们将不胜感激。

最佳答案

Nullable<T>是值类型,generic covariance不适用于值类型(例如,也没有从 IEnumerable<int>IEnumerable<object> 的转换):

Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type.

最简单的修复方法是使用 Cast :

IEnumerable<object> bind2 = list2.Cast<object>();

关于c# - 将可空值列表转换为对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17574966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com