我使用以下代码得到了 Excel 工作表的第一行。
Excel.Range firstRow = ws.UsedRange.Rows[1];
var row = (System.Array) firstRow.Cells.Value;
List<object> Array = row.OfType<object>().ToList();
行
由空值组成。
例如。
问题是当它被转换成列表时,所有的空值都丢失了。 (在这个声明之后)
List<object> Array = row.OfType<object>().ToList();
例如。
有什么想法可以防止这种情况发生吗?
最佳答案
从看你在做什么Cast
会比 OfType
更合适.
List<object> Array = myvalues.Cast<object>().ToList();
这应该做你想做的,基本上只是告诉它所有的对象都应该转换为类型对象。这将保留空值。
差异的原因是OfType
检查 current is TResult
在返回 cast 对象之前,当然还有 null is object
将返回 false,因此它会被丢弃。其推论当然是 Cast
如果使用不当会抛出异常(例如,上面示例中的 Cast<int>
会抛出 InvalidCastException
而 OfType<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/