gpt4 book ai didi

c# - 为什么 的集合无法转换为

转载 作者:可可西里 更新时间:2023-11-01 09:02:24 25 4
gpt4 key购买 nike

为什么 enum 的集合无法转换为 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 方法只能进行装箱/拆箱转换、引用转换以及枚举类型与其基础整数类型之间的转换。不过,拆箱必须是正确的类型 - 它不能拆箱为可为 null 的类型(与 C# 转换不同)。

var collection1 = new[] { Test.A }.Cast<int>()
.Select(x => (int?) x)
.ToList();

对于每个值,Cast 将从装箱的 enum 值拆箱为 int 值,然后是 Select 会将 int 值转换为 int? 值。

在这种情况下,您可以摆脱这个:

var collection1 = new[] { Test.A }.Select(x => (int?) x)
.ToList();

即没有 Cast 步骤。但是,如果您使用的是 object 数组,那就不会起作用:

// Fails
var collection1 = new object[] { Test.A }.Select(x => (int?) x)
.ToList();

您不能将装箱的枚举值取消装箱为可为空的 int 值。 Cast 版本在这种情况下仍然有效,但是,因为它将两个步骤分开(首先拆箱到 int,然后从 int 转换为 int?.)

关于c# - 为什么 <enum> 的集合无法转换为 <int?>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5289188/

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