IsitpossibletocheckfornullvaluesinswitchcasestatementinC#

c#

I have an object with the property Value. Value is a nullable number. I have some scenarios for the value of value. Usually, for null cases, I use the default case but this time, it is not correct logically. I want to do "X" in case of 100, "Y" in case of no value (the value is null), otherwise, I want to do "Z".

switch (p.Value)
{
    case 100:
        // DO X
        break;
    default:
        // Do Z
        break;
}

I tried writing case is null but it doesn't compile: Invalid expression term 'is' (CS1525). Is it possible or should I use if statements instead?

回答

是的,有可能,您已经接近了,只需is从箱子中取出钥匙即可。

switch (p.Value)
{
    case 100:
        // DO X
        break;
    case null:
        // DO Y
        break;
    default:
        // Do Z
        break;
}


以上是IsitpossibletocheckfornullvaluesinswitchcasestatementinC#的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>