欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#8.0中新語法“is{}“的介紹及使用小結(jié)

 更新時間:2023年11月23日 10:02:48   作者:憂郁的蛋~  
is模式匹配操作符通過測試一個變量是否是一個對象,來判斷其是否不為null值,本文主要介紹了C#8.0中新語法“is{}“的介紹及使用小結(jié),感興趣的可以了解一下

一?C#7.0及之前is的使用

is操作符檢查表達式的結(jié)果是否與給定類型兼容,或者(從c# 7.0開始)根據(jù)模式測試表達式。有關(guān)類型測試is操作符的信息,請參閱類型測試和類型轉(zhuǎn)換操作符文章的is操作符部分。

1?is 模式匹配

從C#7.0開始,isswitch語句支持模式匹配。該is關(guān)鍵字支持以下模式:

Type模式:它測試表達式是否可以轉(zhuǎn)換為指定的類型,如果可以,則將其強制轉(zhuǎn)換為該類型的變量。

(Constant)常量模式:用于測試表達式是否求值為指定的常量值。

var模式:匹配成功并且將表達式的值綁定到新的局部變量的匹配。

從C#7.1開始,expr可能具有由通用類型參數(shù)及其約束定義的編譯時類型。
如果exprtrue并且isif語句一起使用,則varname僅在if語句內(nèi)分配。varname的范圍是從is表達式到包含if語句的塊末尾。在其他任何位置使用varname會導(dǎo)致使用尚未分配的變量時產(chǎn)生編譯時錯誤。

1) Type模式

使用類型模式執(zhí)行模式匹配時,is測試表達式是否可以轉(zhuǎn)換為指定的類型,如果可以,將其強制轉(zhuǎn)換為該類型的變量。這是對is語句的直接擴展,可以實現(xiàn)簡潔的類型評估和轉(zhuǎn)換。is類型模式的一般形式是:

expr is type varname

下面的示例使用is類型模式提供類型的IComparable.CompareTo(Object)方法的實現(xiàn)。

using System;

public class Employee : IComparable
{
    public String Name { get; set; }
    public int Id { get; set; }

    public int CompareTo(Object o)
    {
        if (o is Employee e)
        {
            return Name.CompareTo(e.Name);
        }
        throw new ArgumentException("o is not an Employee object.");
    }
}

2) (Constant)常量模式

使用常量模式執(zhí)行模式匹配時,is測試表達式是否等于指定的常量。在C#6和更早版本中,switch語句支持常量模式。從C#7.0開始,該is語句也支持它。其語法為:

expr is constant

以下示例將類型和常量模式組合在一起,以測試對象是否為Dice實例,如果是,則確定擲骰的值是否為6。

using System;
public class Dice
{
    Random rnd = new Random();
    public Dice()
    {
    }
    public int Roll()
    {
        return rnd.Next(1, 7); 
    }
}
class Program
{
    static void Main(string[] args)
    {
        var d1 = new Dice();
        ShowValue(d1);
    }
    private static void ShowValue(object o)
    {
        const int HIGH_ROLL = 6;
        if (o is Dice d && d.Roll() is HIGH_ROLL)
            Console.WriteLine($"The value is {HIGH_ROLL}!");
        else
            Console.WriteLine($"The dice roll is not a {HIGH_ROLL}!");
     }
}
// The example displays output like the following:
//      The value is 6!

null可以使用 (Constant)常量進行檢查。該語句null支持關(guān)鍵字is。其語法為:

expr is null

示例代碼:

using System;
class Program
{
    static void Main(string[] args)
    {
        object o = null;
        if (o is null)
        {
            Console.WriteLine("o does not have a value");
        }
        else
        {
            Console.WriteLine($"o is {o}");
        }
        int? x = 10;
        if (x is null)
        {
            Console.WriteLine("x does not have a value");
        }
        else
        {
            Console.WriteLine($"x is {x.Value}");
        }
        // 'null' check comparison
        Console.WriteLine($"'is' constant pattern 'null' check result : { o is null }");
        Console.WriteLine($"object.ReferenceEquals 'null' check result : { object.ReferenceEquals(o, null) }");
        Console.WriteLine($"Equality operator (==) 'null' check result : { o == null }");
    }
    // The example displays the following output:
    // o does not have a value
    // x is 10
    // 'is' constant pattern 'null' check result : True
    // object.ReferenceEquals 'null' check result : True
    // Equality operator (==) 'null' check result : True
}

3) var模式

與var模式匹配的模式總是成功。它的語法是:

expr is var varname

expr的值總是分配給一個名為varname的局部變量。varname是與expr的編譯時類型相同的變量。

如果expr的計算結(jié)果為null,則is表達式生成true并將null賦值給varname。var模式是is為數(shù)不多的對空值產(chǎn)生true的用法之一。

你可以使用var模式在一個布爾表達式中創(chuàng)建一個臨時變量,如下面的例子所示:

using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
    static void Main()
    {
        int[] testSet = { 100271, 234335, 342439, 999683 };
        var primes = testSet.Where(n => Factor(n).ToList() is var factors
                                    && factors.Count == 2
                                    && factors.Contains(1)
                                    && factors.Contains(n));
        foreach (int prime in primes)
        {
            Console.WriteLine($"Found prime: {prime}");
        }
    }
    static IEnumerable<int> Factor(int number) 
    {
        int max = (int)Math.Sqrt(number);
        for (int i = 1; i <= max; i++) 
        {
            if (number % i == 0)
            {
                yield return i;
                if (i != number / i) 
                {
                    yield return number / i;
                }
            }
        }
    }
}
// The example displays the following output:
//       Found prime: 100271
//       Found prime: 999683

二、C# 8.0中is的新語法

屬性模式

匹配任何非"null"且屬性設(shè)置為Length為2的對象,示例代碼如下:

if (value is { Length: 2 })
{ 
}

實現(xiàn)驗證的示例:

public async Task<IActionResult> Update(string id, ...) 
{
    if (ValidateId(id) is { } invalid)
        return invalid;
    ...
}

上面的例子中,ValidateId()可以返回nullBadObjectRequestResult的一個實例。如果返回了前者,驗證就成功了,并轉(zhuǎn)移到更新主體的其余部分。如果返回的是后者,則is{}為真(也就是說,當(dāng)然BadObjectRequestResult的實例是一個對象),驗證失敗。

如果使用一般寫法做個判斷,可能需要更多的代碼,如下:

public async Task<IActionResult> Update(string id, ...) 
{
    var invalid = ValidateId(id);
    if (invalid != null)
        return invalid;
    ...
}

相關(guān)文檔The `is` operator - Match an expression against a type or constant pattern - C# | Microsoft Learn

到此這篇關(guān)于C#8.0中新語法“is {}“的介紹及使用小結(jié)的文章就介紹到這了,更多相關(guān)C#8.0 is {}內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論