简体   繁体   English

C#NullReference Exception和ReSharper建议

[英]C# NullReference Exception and ReSharper suggestion

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 : Resharper给我一个错误(我是ReSharper的新手...我正在尝试它)它建议我:

  if (((string) lstProperty[i].PropertyIdentifier).CompareTo("Name") == 0)

Why is the second is NullException safe? 为什么第二个是NullException安全? For me both will crash if null value appear? 对我来说,如果出现空值,两者都会崩溃?

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. 如果无法执行强制转换,则“as”运算符将返回null,而如果无法强制转换,则C样式强制转换将抛出异常。

I suggest breaking this out into multiple statements: 我建议将其分解为多个语句:

string propertyIdentifier = lstProperty[u].PropertyIdentifier as string;
if(propertyIdentifier != null && propertyIdentifier.CompareTo("Name") == 0)
{
    ... your if statement ...
}

Resharper shouldn't complain about this, and you also won't get a NullReferenceException if the PropertyIdentifier is null or not a string. Resharper不应该抱怨这个,如果PropertyIdentifier为null或者不是字符串,你也不会得到NullReferenceException。

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 ). 当它们失败时,结果会略有不同:第二个示例稍早失败(在转换时),并且具有更具体的异常( InvalidCastExceptionNullReferenceException )。

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. 具体来说,如果PropertyIdentifier为null而非string ,则可以在第二种情况下告知,但不能在第一种情况下告知。

Also, if you are in a try/catch , you can handle the non- string case in a separate code path than the null case. 此外,如果您在try/catch ,则可以在单独的代码路径中处理非string大小写,而不是null大小写。 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: 如果您在各种情况下单步执行以下代码,它可能有助于说明情况:

var propertyI = lstProperty[i];
var propertyIdentifier = propertyI.PropertyIdentifier;

// pick one of these:
var propertyIdentifierAsString = propertyIdentifier as string;
var propertyIdentifierAsString = (string)propertyIdentifier;

if (propertyIdentifierAsString.CompareTo("Name") == 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM