当前位置: 首页 > 科技观察

如何在C#8中使用模式匹配

时间:2023-03-18 14:03:07 科技观察

转载本文请联系码农阅读公众号。模式匹配是C#7中引入的一个非常重要的特性。你可以在任何类型上使用模式匹配,甚至是自定义类型,并且在C#8中得到了增强,引入了大量新的模式类型,本文将讨论如何使用C#8中的模式匹配C#8中的表达式模式C#8中可以通过三种不同的方式来表达这种模式。Location模式Attribute模式Tuple模式下面我们就来看看这些模式的相关代码和使用场景。Location模式location模式主要是利用类中的Deconstruct方法,将类中的属性解构为一些分散的变量,然后实现对这些分散变量的比较。如果您有点困惑,请考虑以下Rectangle类。publicclassRectangle{publicintLength{get;set;}publicintBreadth{get;set;}publicRectangle(intx,inty)=>(Length,Breadth)=(x,y);publicvoidDeconstruct(outintx,outinty)=>(x,y)=(Length,Breadth);}接下来我们看看如何在Rectangle上使用position模式。staticvoidMain(string[]args){Rectanglerectangle=newRectangle(10,10);varresult=rectanglesswitch{Rectangle(0,0)=>"Thevalueoflengthandbreadthiszero.",Rectangle(10,10)=>"Thevalueoflengthandbreadthissame–thisrepresentsasquare.",Rectangle(10,5)=>"Thevalueolengthis10,breadthis5.",_=>"Default."};Console.WriteLine(result);}如果你还一头雾水,继续看最后生成的IL代码,就是一目了然。privatestaticvoidMain(string[]args){Rectanglerectangle=newRectangle(10,10);if(1==0){}if(rectangle==null){gotoIL_0056;}rectangle.Deconstruct(outintx,outinty);stringtext;if(x!=0){if(x!=10){gotoIL_0056;}if(y!=5){if(y!=10){gotoIL_0056;}text="Thevalueoflengthandbreadthissame–thisrepresentsasquare.";}else{text="Thevalueoflengththis10,breadthis5.";}}else{if(y!=0){gotoIL_0056;}text="Thevalueoflengthandbreadthiszero.";}gotoIL_005e;IL_0056:text="Default.";gotoIL_005e;IL_005e:if(1==0){}stringresult=text;Console.WriteLine(result);}C#8的属性模式属性模式常用于实现基于类中属性的比较,考虑下面的Employee类。publicclassEmployee{publicintId{get;个人所得税计算。publicstaticdecimalComputeIncomeTax(Employeeemployee,decimalsalary)=>employeeswitch{{国家:“加拿大”}=>(工资*21)/100,{国家:“阿联酋”}=>0,{国家:“印度”}=>(工资*30)/100,_=>0};接下来我们看看如何调用,代码如下。staticvoidMain(string[]args){Employeeemployee=newEmployee(){Id=1,FirstName="Michael",LastName="Stevens",Salary=5000,Country="Canada"};decimalincometax=ComputeIncometax(雇员,雇员。Salary);Console.WriteLine("Theincometaxis{0}",incometax);Console.Read();}C#8的元组模式元组模式是另一种模式类型,常用于同时测试多个输入值同时。下面的代码片段展示了如何使用元组模式。staticvoidMain(string[]args){staticstringGetLanguageNames(stringteam1,stringteam2)=>(team1,team2)switch{("C++","Java")=>"C++andJava.",("C#","Java")=>"C#andJava.",("C++","C#")=>"C++andC#.",(_,_)=>"Invalidinput"};(字符串,字符串,字符串,string)programmingLanguages=("C++","Java","C#","F#");varlanguage1=programmingLanguages.Item1.ToString();varlanguage2=programmingLanguages.Item3.ToString();Console.WriteLine($"选择的语言是:{GetLanguageNames(language1,language2)}");}在C#8中,对模式匹配进行了多项增强,使代码更易读、更易维护、更高效,这也是程序员的特色之一盼了这么多年。翻译链接:https://www.infoworld.com/article/3518431/how-to-use-pattern-matching-in-csharp-80.html