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開始,is
和switch
語句支持模式匹配。該is
關(guān)鍵字支持以下模式:
Type模式:它測試表達式是否可以轉(zhuǎn)換為指定的類型,如果可以,則將其強制轉(zhuǎn)換為該類型的變量。
(Constant)常量模式:用于測試表達式是否求值為指定的常量值。
var模式:匹配成功并且將表達式的值綁定到新的局部變量的匹配。
從C#7.1開始,expr
可能具有由通用類型參數(shù)及其約束定義的編譯時類型。
如果expr
是true
并且is
與if
語句一起使用,則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()
可以返回null
或BadObjectRequestResult
的一個實例。如果返回了前者,驗證就成功了,并轉(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)文章
C#中DataSet、DataTable、DataRow數(shù)據(jù)的復(fù)制方法
這篇文章介紹了C#中DataSet、DataTable、DataRow數(shù)據(jù)的復(fù)制方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07C# Entity Framework中的IQueryable和IQueryProvider詳解
這篇文章主要介紹了C# Entity Framework中的IQueryable和IQueryProvider詳解,本文使用實例分析這兩個接口的內(nèi)部實現(xiàn),需要的朋友可以參考下2015-01-01C#中System.Array.CopyTo() 和 System.Array.Clon()&nbs
System.Array.CopyTo()和System.Array.Clone()是用于數(shù)組復(fù)制的兩種不同方法,本文就來介紹C,#中System.Array.CopyTo() 和 System.Array.Clon() 的區(qū)別,具有一定的參考價值,感興趣的可以了解一下2024-04-04C#實現(xiàn)ComboBox控件顯示出多個數(shù)據(jù)源屬性的方法
這篇文章主要介紹了C#實現(xiàn)ComboBox控件顯示出多個數(shù)據(jù)源屬性的方法,實例分析了ComboBox控件的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09C#刪除只讀文件或文件夾(解決File.Delete無法刪除文件)
這篇文章主要介紹了C#刪除只讀文件或文件夾(解決File.Delete無法刪除文件),需要的朋友可以參考下2015-09-09C#實現(xiàn)操作windows系統(tǒng)服務(wù)(service)的方法
這篇文章主要介紹了C#實現(xiàn)操作windows系統(tǒng)服務(wù)(service)的方法,可實現(xiàn)系統(tǒng)服務(wù)的啟動和停止功能,非常具有實用價值,需要的朋友可以參考下2015-04-04