将数组从可空类型转换为相同类型的不可空类型? [英] Convert array from nullable type to non-nullable of same type?
问题描述
我想将 Nullable(Of Byte)()
数组(又名 byte?[]
)转换为相同类型的非空数组,即是,从 byte?[]
到 byte[]
.
I would like to convert a Nullable(Of Byte)()
array (a.k.a. byte?[]
) to a non-nullable array of the same type, that is, from byte?[]
to byte[]
.
我正在寻找 C# 或 VB.NET 中更简单、更容易、更快的通用解决方案.我找到了 this 通用函数来在可为空类型之间进行转换,但我找不到一种方法来使转换逻辑适应从可空类型转换为不可空类型.
I'm looking for the simpler, easier, faster generic solution, in C# or VB.NET. I've found this generic function to convert between nullable types but I can't find a way to adapt the conversion logic to convert from a nullable type to a non-nullable type.
这是一个代码示例,我觉得需要对其执行这种转换:
This is a code example for which I feel the need to perform that kind of conversion:
byte?[] data = {1, 0, 18, 22, 255};
string hex = BitConverter.ToString(data).Replace("-", ", ");
推荐答案
要将一种类型的数组转换为另一种类型的数组,请使用 Array.ConvertAll 方法:
To convert an array of one type to an array of another type, use the Array.ConvertAll method:
byte?[] data = { 1, 0, 18, 22, 255 };
byte[] result = Array.ConvertAll(data, x => x ?? 0);
这比使用 LINQ 更简单、更容易、更快.
This is simpler, easier, and faster than using LINQ.
这篇关于将数组从可空类型转换为相同类型的不可空类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!