C#8.0中新語(yǔ)法“is{}“的介紹及使用小結(jié)
一?C#7.0及之前is的使用
is
操作符檢查表達(dá)式的結(jié)果是否與給定類型兼容,或者(從c# 7.0開(kāi)始)根據(jù)模式測(cè)試表達(dá)式。有關(guān)類型測(cè)試is
操作符的信息,請(qǐng)參閱類型測(cè)試和類型轉(zhuǎn)換操作符文章的is操作符部分。
1?is 模式匹配
從C#7.0開(kāi)始,is
和switch
語(yǔ)句支持模式匹配。該is
關(guān)鍵字支持以下模式:
Type模式:它測(cè)試表達(dá)式是否可以轉(zhuǎn)換為指定的類型,如果可以,則將其強(qiáng)制轉(zhuǎn)換為該類型的變量。
(Constant)常量模式:用于測(cè)試表達(dá)式是否求值為指定的常量值。
var模式:匹配成功并且將表達(dá)式的值綁定到新的局部變量的匹配。
從C#7.1開(kāi)始,expr
可能具有由通用類型參數(shù)及其約束定義的編譯時(shí)類型。
如果expr
是true
并且is
與if
語(yǔ)句一起使用,則varname
僅在if語(yǔ)句內(nèi)分配。varname
的范圍是從is
表達(dá)式到包含if
語(yǔ)句的塊末尾。在其他任何位置使用varname
會(huì)導(dǎo)致使用尚未分配的變量時(shí)產(chǎn)生編譯時(shí)錯(cuò)誤。
1) Type模式
使用類型模式執(zhí)行模式匹配時(shí),is
測(cè)試表達(dá)式是否可以轉(zhuǎn)換為指定的類型,如果可以,將其強(qiáng)制轉(zhuǎn)換為該類型的變量。這是對(duì)is
語(yǔ)句的直接擴(kuò)展,可以實(shí)現(xiàn)簡(jiǎn)潔的類型評(píng)估和轉(zhuǎn)換。is類型模式的一般形式是:
expr is type varname
下面的示例使用is類型模式提供類型的IComparable.CompareTo(Object)方法的實(shí)現(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í)行模式匹配時(shí),is測(cè)試表達(dá)式是否等于指定的常量。在C#6和更早版本中,switch語(yǔ)句支持常量模式。從C#7.0開(kāi)始,該is語(yǔ)句也支持它。其語(yǔ)法為:
expr is constant
以下示例將類型和常量模式組合在一起,以測(cè)試對(duì)象是否為Dice實(shí)例,如果是,則確定擲骰的值是否為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)常量進(jìn)行檢查。該語(yǔ)句null
支持關(guān)鍵字is
。其語(yǔ)法為:
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模式匹配的模式總是成功。它的語(yǔ)法是:
expr is var varname
expr
的值總是分配給一個(gè)名為varname
的局部變量。varname
是與expr
的編譯時(shí)類型相同的變量。
如果expr
的計(jì)算結(jié)果為null
,則is
表達(dá)式生成true
并將null
賦值給varname
。var模式是is
為數(shù)不多的對(duì)空值產(chǎn)生true
的用法之一。
你可以使用var模式在一個(gè)布爾表達(dá)式中創(chuàng)建一個(gè)臨時(shí)變量,如下面的例子所示:
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的新語(yǔ)法
屬性模式
匹配任何非"null"
且屬性設(shè)置為L(zhǎng)ength為2的對(duì)象,示例代碼如下:
if (value is { Length: 2 }) { }
實(shí)現(xiàn)驗(yàn)證的示例:
public async Task<IActionResult> Update(string id, ...) { if (ValidateId(id) is { } invalid) return invalid; ... }
上面的例子中,ValidateId()
可以返回null
或BadObjectRequestResult
的一個(gè)實(shí)例。如果返回了前者,驗(yàn)證就成功了,并轉(zhuǎn)移到更新主體的其余部分。如果返回的是后者,則is{}
為真(也就是說(shuō),當(dāng)然BadObjectRequestResult
的實(shí)例是一個(gè)對(duì)象),驗(yàn)證失敗。
如果使用一般寫法做個(gè)判斷,可能需要更多的代碼,如下:
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中新語(yǔ)法“is {}“的介紹及使用小結(jié)的文章就介紹到這了,更多相關(guān)C#8.0 is {}內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#交錯(cuò)數(shù)組知識(shí)點(diǎn)分析
在本篇文章里小編給大家整理的是關(guān)于C#交錯(cuò)數(shù)組知識(shí)點(diǎn)分析,需要的朋友們參考下。2019-11-11C#中DataSet、DataTable、DataRow數(shù)據(jù)的復(fù)制方法
這篇文章介紹了C#中DataSet、DataTable、DataRow數(shù)據(jù)的復(fù)制方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07C# Entity Framework中的IQueryable和IQueryProvider詳解
這篇文章主要介紹了C# Entity Framework中的IQueryable和IQueryProvider詳解,本文使用實(shí)例分析這兩個(gè)接口的內(nèi)部實(shí)現(xiàn),需要的朋友可以參考下2015-01-01C#中System.Array.CopyTo() 和 System.Array.Clon()&nbs
System.Array.CopyTo()和System.Array.Clone()是用于數(shù)組復(fù)制的兩種不同方法,本文就來(lái)介紹C,#中System.Array.CopyTo() 和 System.Array.Clon() 的區(qū)別,具有一定的參考價(jià)值,感興趣的可以了解一下2024-04-04C#實(shí)現(xiàn)ComboBox控件顯示出多個(gè)數(shù)據(jù)源屬性的方法
這篇文章主要介紹了C#實(shí)現(xiàn)ComboBox控件顯示出多個(gè)數(shù)據(jù)源屬性的方法,實(shí)例分析了ComboBox控件的使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-09-09C#實(shí)現(xiàn)簡(jiǎn)單的loading提示控件實(shí)例代碼
本文通過(guò)實(shí)例代碼給大家介紹了C#實(shí)現(xiàn)簡(jiǎn)單的loading提示控件功能,代碼非常簡(jiǎn)單,具有參考借鑒價(jià)值,需要的朋友參考下吧2017-09-09C#刪除只讀文件或文件夾(解決File.Delete無(wú)法刪除文件)
這篇文章主要介紹了C#刪除只讀文件或文件夾(解決File.Delete無(wú)法刪除文件),需要的朋友可以參考下2015-09-09C#實(shí)現(xiàn)操作windows系統(tǒng)服務(wù)(service)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)操作windows系統(tǒng)服務(wù)(service)的方法,可實(shí)現(xiàn)系統(tǒng)服務(wù)的啟動(dòng)和停止功能,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04