c# – 为什么一个集合无法投射到?
发布时间:2020-12-15 18:07:54 所属栏目:百科 来源:网络整理
导读:为什么枚举集合不能转换为int? enum Test { A = 1,B = 2 };int? x = (int?)Test.A; // Validvar collection1 = new[] { Test.A }.Castint().ToList();// InvalidCastException has thrown (Specified cast is not valid.) var collection2 = new[] { Test.A
为什么枚举集合不能转换为int?
enum Test { A = 1,B = 2 }; int? x = (int?)Test.A; // Valid var collection1 = new[] { Test.A }.Cast<int>().ToList(); // InvalidCastException has thrown (Specified cast is not valid.) var collection2 = new[] { Test.A }.Cast<int?>().ToList(); 解决方法
Cast方法只能在枚举类型及其基础整合类型之间进行拳击/拆箱转换,引用转换和转换.拆箱必须是正确的类型 – 它不能unbox到可空类型(不像C#转换).
var collection1 = new[] { Test.A }.Cast<int>() .Select(x => (int?) x) .ToList(); 对于每个值,Cast将从boxed枚举值中取消框到int值,然后Select将int值转换为int?值. 在这种情况下,您也可以避免以下情况: var collection1 = new[] { Test.A }.Select(x => (int?) x) .ToList(); 即无铸造步骤.但是,如果您有对象数组,则不起作用: // Fails var collection1 = new object[] { Test.A }.Select(x => (int?) x) .ToList(); 您无法将boxed枚举值解压缩为可空的int值.然而,在这种情况下,Cast版本仍然可以工作,因为它拆分了两个步骤(首先取消装箱到int,然后从int转换为int?). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |