在此使用“是".关键字为"null"的关键字关键字c#7.0 [英] Using "is" keyword with "null" keyword c# 7.0

查看:136
本文介绍了在此使用“是".关键字为"null"的关键字关键字c#7.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我发现,以下代码可以按预期在VS2017中编译和运行.但是我找不到关于此的任何主题/文档.所以我很好奇使用这种语法是否合法:

Recently i find out, that the following code compiles and works as expected in VS2017. But i can't find any topic/documentation on this. So i'm curious is it legit to use this syntax:

class Program
{
    static void Main(string[] args)
    {
        var o = new object();              
        Console.WriteLine(o is null);
        o = null;
        Console.WriteLine(o is null);
        Console.ReadLine();
    }
}

顺便说一句,这在VS2015中不起作用

BTW this is not working in VS2015

推荐答案

是的,它完全有效.这使用了C#7的模式匹配功能,该功能可用于is表达式和switch/case语句. (它需要C#7的事实就是为什么它在VS2015中对您不起作用的原因.)例如:

Yes, it's entirely valid. This uses the pattern matching feature of C# 7, which is available with is expressions and switch/case statements. (The fact that it requires C# 7 is why it isn't working for you in VS2015.) For example:

// Type check, with declaration of new variable
if (o is int i)
{
    Console.WriteLine(i * 10);
}
// Simple equality check
if (o is 5)  {}

一样进行质量检查-特别是对于null-在is模式匹配中不太有用,但是在switch/case中更有用:

Equality checks like the latter - particularly for null - aren't likely to be very useful for is pattern matching, but are more useful for switch/case:

switch (o)
{
    case int i when i > 100000:
        Console.WriteLine("Large integer");
        break;
    case null:
        Console.WriteLine("Null value");
        break;
    case string _:
        Console.WriteLine("It was a string");
        break;
    default:
        Console.WriteLine("Not really sure");
        break;
}

有关C#7功能的更多详细信息,请参见

For more details of C# 7 features, see the MSDN blog post by Mads Torgersen.

这篇关于在此使用“是".关键字为"null"的关键字关键字c#7.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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