'is' 与带空检查的 try cast [英] 'is' versus try cast with null check
问题描述
我注意到 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 建议优化更改和代码减少更改,但这感觉就像它想把我的单个语句变成两行.
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:
is 表达式 如果满足以下两个条件,则计算结果为真满足:
An is expression evaluates to true if both of the following conditions are met:
表达式 不为空.表达式可以转换为类型.这是一个(type)(expression)
形式的强制转换表达式将在没有抛出异常.
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.
我是否误读了,或者 is
没有执行完全相同的检查,只是在一行中而不需要为空检查显式创建另一个局部变量?
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
...
}
<小时>
C# 7.0 使用模式匹配支持更紧凑的语法:
if (myObj.myProp is MyType myObjRef)
{
...
}
这篇关于'is' 与带空检查的 try cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!