2017-07-11 125 views
-7

我有这个条件空条件运算符是否返回false如果为空?

if (item?.Value2?.GetType() != typeof(string) && item.get_Value() == 0)

我相信,如果项目是空的?.操作将返回null,我相信会被解析为false导致病情短路和一切都会好起来(item.get_Value()将不会被调用)

但是我不能肯定,我想也许我需要做的是,像这样

if (item?.Value2?.GetType() ?? 0 != typeof(string) && item.get_Value() == 0)

但我认为这可能是矫枉过正,是第一种安全的潜在空引用异常吗?

+8

没有必要对“信仰”的编程。你可以随时启动编译器并测试它。 –

+0

是一个单元格Excel范围项目?你想检查单元格值是否为0或显示的格式文本是否为“0”?这是矫枉过正,缺少很多边缘案例。 – Slai

+4

为什么不只是1. [阅读文档](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators)和/或2.尝试一下亲眼看看? –

回答

5

item?.Value2?.GetType()将返回null如果itemnullValue2null

评价将是

if (null != typeof(string) && item.get_Value() == 0) 

所以第一个条件将被解析成true引起的病症的NullReferenceExceptionitem.get_Value() == 0将被执行(但只有当itemnull,而不是Value2

+0

@RufusL'null!= typeof(string)'将评估为'true' – Alberto

+0

@hellyale它取决于,'get_Value()'的返回值是什么? – Alberto

+0

@hellyale如果'item'为null,那么'item?.get_value()'将返回null,并且表达式'item?.get_Value()== 0'将被赋值为'false' – Alberto

1

.Value2速度更快,但对于格式为日期或货币的单元格,.Value2返回Double,但.Value.get_Value()返回DateTim e和小数。如果单元格是数字类型,则两者都会导致Double;如果值不是数字类型或数字格式为文本,则两者都会导致String。返回类型也可以为布尔值为TRUE和FALSE,整数为错误。


if (0.0.Equals(item.Value2)) // if (item.Value2 is Double && (Double)(item.Value2) == 0.0) 

这可能看起来很奇怪,但它是检查是否运行时type is Double and equal 0.0最短和最安全的方式。 (项不为空,如果它是枚举范围的结果)


至于实际的问题,找到的第0细胞:

Range cell = range.Find(0, LookAt: XlLookAt.xlWhole); 
if (cell != null) { /* ... */ }