简体   繁体   English

将枚举的所有选项填充为Nullable <Enum> 排列

[英]Fill all options of an Enum into Nullable<Enum> array

I have an Enum that needs to go into an Array that is Nullable : 我有一个Enum ,需要进入一个Nullable Array

StatusType?[] statusTypes = null; //Array to fill

I tried to fill the statusTypes like this: 我试图像这样填充statusTypes

statusTypes = (StatusType?[])Enum.GetValues(typeof(StatusType))

I receive the following error: 我收到以下错误:

System.InvalidCastException: 'Unable to cast object of type 'x.Entities.Enums.StatusType[]' to type 'System.Nullable`1[x.Entities.Enums.StatusType][]'.' System.InvalidCastException:'无法将类型'x.Entities.Enums.StatusType []'的对象强制转换为类型'System.Nullable`1 [x.Entities.Enums.StatusType] []'。

How can I fill the Enum?[] with Enum[] ? 如何用Enum[]填充Enum?[] Enum[] I'm sure it is any easy fix, but I have been stumpted on it for a bit now. 我敢肯定,这很容易解决,但是现在我对此感到困惑。 Thank you. 谢谢。

使用LINQ的Cast<T>()扩展方法并提供目标类型:

statusTypes = Enum.GetValues(typeof(StatusType)).Cast<StatusType?>().ToArray();

You can't just cast the arrays. 您不能只转换数组。 The types are not compatible. 类型不兼容。 You can use Array.ConvertAll to do the convertion: 您可以使用Array.ConvertAll进行转换:

Array.ConvertAll((StatusType[])Enum.GetValues(typeof(StatusType)), x => (StatusType?)x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM