c# - 如何在 system.array - C# 中保留 null?

标签 c# .net excel system.array

我使用以下代码得到了 Excel 工作表的第一行。

Excel.Range firstRow = ws.UsedRange.Rows[1];
var row = (System.Array) firstRow.Cells.Value;
List<object> Array = row.OfType<object>().ToList();

由空值组成。

例如。 enter image description here

问题是当它被转换成列表时,所有的空值都丢失了。 (在这个声明之后)

 List<object> Array = row.OfType<object>().ToList();

例如。 enter image description here

有什么想法可以防止这种情况发生吗?

最佳答案

从看你在做什么Cast会比 OfType 更合适.

List<object> Array = myvalues.Cast<object>().ToList();

这应该做你想做的,基本上只是告诉它所有的对象都应该转换为类型对象。这将保留空值。

差异的原因是OfType检查 current is TResult在返回 cast 对象之前,当然还有 null is object将返回 false,因此它会被丢弃。其推论当然是 Cast如果使用不当会抛出异常(例如,上面示例中的 Cast<int> 会抛出 InvalidCastExceptionOfType<int> 只会返回可以转换为整数的项。

发件人: CAST AND OFTYPE

There’s one important case to consider where Cast will successfully return a value and OfType will ignore it: null references (with a nullable return type). In normal code, you can cast a null reference to any nullable type (whether that’s a reference type or a nullable value type). However, if you use the "is" C# operator with a null value, it will always return false. Cast and OfType follow the same rules, basically.

关于c# - 如何在 system.array - C# 中保留 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27105402/

相关文章:

c# - 在 Entity Framework 中保存实体的通用方法

c# - 从 Javascript 调用 C# 方法

c# - 除非标记为UNSAFE,否则C#CLR会引发安全异常

.net - 在 Azure CI 构建期间找不到任何程序集

vba - 设置十六进制和十进制颜色的行为不同

c# - ASP.NET WebAPI - [FromBody] 的问题

c# - 使用自定义运算符组合 Lambda 表达式

.net - 什么是Windows编程以及它的发展方向?老实说,win32已经死了,不是吗? [复制]

python - Pandas excel 到 python 的长列

vba - 粘贴与 PasteSpecial