C# NullReference 异常和 ReSharper 建议
这就是我所写的:
if ((lstProperty[i].PropertyIdentifier as string).CompareTo("Name") == 0)
Resharper 给我一个错误(我是 ReSharper 的新手...我正在尝试),它建议我:
if (((string) lstProperty[i].PropertyIdentifier).CompareTo("Name") == 0)
为什么第二个是 NullException 安全的? 对我来说,如果出现空值,两者都会崩溃?
This is what I have written:
if ((lstProperty[i].PropertyIdentifier as string).CompareTo("Name") == 0)
Resharper put me an error (I am new with ReSharper... I am trying it) and it suggests me :
if (((string) lstProperty[i].PropertyIdentifier).CompareTo("Name") == 0)
Why is the second is NullException safe? For me both will crash if null value appear?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两个示例在相同的情况下都会成功或失败,并且当它们成功时,行为将是相同的。
当它们失败时,结果会略有不同:第二个示例稍早失败(在强制转换时),并出现更具体的异常(
InvalidCastException
与NullReferenceException
)。主要好处是调试:当它们失败时,您可以比第一个示例获得更多有关第二个示例失败原因的信息。 具体来说,如果 PropertyIdentifier 为
null
与非string
,您可以区分第二种情况,但不能区分第一种情况。此外,如果您处于
try/catch
中,则可以在单独的代码路径中处理非string
情况,而不是null
情况。 但是,您可能不应该这样编码:如果您这样做,那么您就做错了其他事情。如果您在各种情况下逐步执行以下代码,可能有助于阐明情况:
Both examples will succeed or fail in the same circumstances, and when they succeed, the behavior will be identical.
When they fail, the result will be slightly different: the second example fails slightly earlier (at the cast), and with a more specific exception (
InvalidCastException
vs.NullReferenceException
).The main benefit is for debugging: when they fail, you have more information about why it failed in the second example than in the first. Specifically, if the PropertyIdentifier is
null
vs. non-string
, you can tell in the second case, but not in the first case.Also, if you are in a
try/catch
, you can handle the non-string
case in a separate code path than thenull
case. However, you probably shouldn't be coding this way: if you are, you're doing something else wrong.It might help illuminate the situation if you step through the following code in the various cases:
如果无法执行强制转换,“as”运算符将返回 null,而 C 风格强制转换如果无法执行,将抛出异常。
我建议将其分解为多个语句:
Resharper 不应抱怨这一点,并且如果 PropertyIdentifier 为 null 或不是字符串,您也不会得到 NullReferenceException。
The 'as' operator will return null if the cast cannot be executed, while a C-style cast will throw an exception if it can't cast.
I suggest breaking this out into multiple statements:
Resharper shouldn't complain about this, and you also won't get a NullReferenceException if the PropertyIdentifier is null or not a string.