gpt4 book ai didi

c# - 'is' 与 try cast with null check

转载 作者:IT王子 更新时间:2023-10-29 03:35:56 26 4
gpt4 key购买 nike

我注意到 Resharper 建议我打开这个:

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

进入这个:

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

为什么它会建议进行此更改?我习惯了 Resharper 建议优化更改和代码减少更改,但这感觉就像它想把我的单一语句变成两行。

根据 MSDN :

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

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 没有做完全相同的检查,只是在一行中而不需要为空检查显式创建另一个局部变量?

最佳答案

因为只有一个 Actor 。比较一下:

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 使用 pattern matching 支持更紧凑的语法:

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

关于c# - 'is' 与 try cast with null check,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13405714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com