'是'与尝试投用null检查 [英] 'is' versus try cast with null check

查看:173
本文介绍了'是'与尝试投用null检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现ReSharper的建议我把这个:

I noticed that Resharper suggests that I turn this:

if (myObj.myProp is MyType)
{
   ...
}

这个:

var myObjRef = myObj.myProp as MyType;
if (myObjRef != null)
{
   ...
}

为什么会提出这种变化?我已经习惯了ReSharper的建议优化变化和code折减的变化,但这种感觉就像它希望把我的一条语句,并把它变成一个两班轮。

Why would it suggest this change? I'm used to Resharper suggesting optimization changes and code reduction changes, but this feels like it wants to take my single statement and turn it into a two-liner.

根据 MSDN

这是 EX pression 的计算结果为真,如果同时满足以下两个条件   满足:

An is expression evaluates to true if both of the following conditions are met:

EX pression 的是不为空。 EX pression可以转换为的键入的。这是一个   投形式的前pression (类)(如pression)将完成无   抛出异常。

expression is not null. expression can be cast to type. That is, a cast expression of the form (type)(expression) will complete without throwing an exception.

我是误读了,或者不做同样的检查,只是在一个单一的线,但无明确创建为空检查另一个局部变量需要?

Am I misreading that, or doesn't is do the exact same checks, just in a single line without the need to explicitly create another local variable for the null check?

推荐答案

由于只有一个演员。与此相比:

Because there's only one cast. Compare this:

if (myObj.myProp is MyType) // cast #1
{
    var myObjRef = (MyType)myObj.myProp; // needs to be cast a second time
                                         // before using it as a MyType
    ...
}

这样:

var myObjRef = myObj.myProp as MyType; // only one cast
if (myObjRef != null)
{
    // myObjRef is already MyType and doesn't need to be cast again
    ...
}

这篇关于'是'与尝试投用null检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆