带有空检查的 C# 7 switch case [英] C# 7 switch case with null checks

查看:82
本文介绍了带有空检查的 C# 7 switch case的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#7 引入了一个名为 patterns 的新功能,您可以将其用于 Is-Expression 或 Switch 案例,如下所示:

C#7 introduces a new feature called patterns, which you can use with Is-Expression or Switch cases like this:

string str = null; 
switch(str){
    case string x:
        Console.WriteLine("string " + x);
        break;
    default:
        Console.WriteLine("default");
        break;
}

并且您会期望它会进入案例 #1,因为它是相同的类型,但事实并非如此.

and you would expect that it will goes inside case #1, as it is the same type, but it didn't.

推荐答案

尽管您可能会这么想,string x = null 实际上根本不是字符串.它是无",分配给字符串类型的变量.

Despite what you might think, string x = null actually isn't a string at all. It is 'nothing', assigned to a variable of type string.

在你的开关中的检查基本上与 null is string 相同,它是 false 已经很长时间了.这是使用泛型评估类型时的常见问题,但它也有其优点.

The check in your switch is basically the same as null is string which is false for a long time already. This is a common issue when evaluating types with generics, but it has its plus sides too.

在幕后,is 使用 as,并带有空检查.所以这就是它不能返回 true 的原因.您可以说 is 运算符的逻辑如下:

Under the hood, is uses as, with a null check. So that is why it can't return true. You could say the logic for the is operator is as follows:

is = (null as string) != null

这篇关于带有空检查的 C# 7 switch case的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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