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

本文转载自微信公众号「码农读书」,作者码农读书 。转载本文请联系码农读书公众号。

成都创新互联成立10余年来,这条路我们正越走越好,积累了技术与客户资源,形成了良好的口碑。为客户提供网站制作、成都网站设计、网站策划、网页设计、国际域名空间、网络营销、VI设计、网站改版、漏洞修补等服务。网站是否美观、功能强大、用户体验好、性价比高、打开快等等,这些对于网站建设都非常重要,成都创新互联通过对建站技术性的掌握、对创意设计的研究为客户提供一站式互联网解决方案,携手广大客户,共同发展进步。

模式匹配 是在 C# 7 中引入的一个非常??的特性,你可以在任何类型上使用 模式匹配,甚至是自定义类型,而且在 C# 8 中得到了增强,引入了大量的新模式类型,这篇文章就来讨论如何在 C# 8 中使用模式匹配。

C# 8 中的表达式模式

在 C# 8 中有三种不同的方式来表达这种模式。

  • 位置模式
  • 属性模式
  • Tuple模式

接下来看一下这些模式的相关代码及使用场景。

位置模式

位置模式主要利用类中的 Deconstruct 方法将类中的属性解构到一些零散的变量中,然后实现这些零散变量的比较,如果有点懵的话,考虑下面的 Rectangle 类。

 
 
 
 
  1. public class Rectangle
  2.    {
  3.        public int Length { get; set; }
  4.        public int Breadth { get; set; }
  5.        public Rectangle(int x, int y) => (Length, Breadth) = (x, y);
  6.        public void Deconstruct(out int x, out int y) => (x, y) = (Length, Breadth);
  7.    }

接下来看一下如何在 Rectangle 上使用 位置模式。

 
 
 
 
  1. static void Main(string[] args)
  2.         {
  3.             Rectangle rectangle = new Rectangle(10, 10);
  4.             var result = rectangle switch
  5.             {
  6.                 Rectangle(0, 0) => "The value of length and breadth is zero.",
  7.                 Rectangle(10, 10) => "The value of length and breadth is same – this represents a square.",
  8.                 Rectangle(10, 5) => "The value of length is 10, breadth is 5.",
  9.                 _ => "Default."
  10.             };
  11.             Console.WriteLine(result);
  12.         }

如果还是蒙的话继续看看最终生成的 IL 代码,一目了然。

 
 
 
 
  1. private static void Main(string[] args)
  2. {
  3.  Rectangle rectangle = new Rectangle(10, 10);
  4.  if (1 == 0)
  5.  {
  6.  }
  7.  if (rectangle == null)
  8.  {
  9.   goto IL_0056;
  10.  }
  11.  rectangle.Deconstruct(out int x, out int y);
  12.  string text;
  13.  if (x != 0)
  14.  {
  15.   if (x != 10)
  16.   {
  17.    goto IL_0056;
  18.   }
  19.   if (y != 5)
  20.   {
  21.    if (y != 10)
  22.    {
  23.     goto IL_0056;
  24.    }
  25.    text = "The value of length and breadth is same – this represents a square.";
  26.   }
  27.   else
  28.   {
  29.    text = "The value of length is 10, breadth is 5.";
  30.   }
  31.  }
  32.  else
  33.  {
  34.   if (y != 0)
  35.   {
  36.    goto IL_0056;
  37.   }
  38.   text = "The value of length and breadth is zero.";
  39.  }
  40.  goto IL_005e;
  41.  IL_0056:
  42.  text = "Default.";
  43.  goto IL_005e;
  44.  IL_005e:
  45.  if (1 == 0)
  46.  {
  47.  }
  48.  string result = text;
  49.  Console.WriteLine(result);
  50. }

C# 8 的 属性模式

属性模式常用于实现基于类中属性的比较,考虑下面的 Employee 类。

 
 
 
 
  1. public class Employee
  2.     {
  3.         public int Id { get; set; }
  4.         public string FirstName { get; set; }
  5.         public string LastName { get; set; }
  6.         public decimal Salary { get; set; }
  7.         public string Country { get; set; }
  8.     }

下面的代码片段展示了如何利用 属性模式 实现 employee 的个人所得税计算。

 
 
 
 
  1. public static decimal ComputeIncomeTax(Employee employee, decimal salary) => employee switch
  2.         {
  3.             { Country: "Canada" } => (salary * 21) / 100,
  4.             { Country: "UAE" } => 0,
  5.             { Country: "India" } => (salary * 30) / 100,
  6.             _ => 0
  7.         };

接下来看一下如何调用,代码如下。

 
 
 
 
  1. static void Main(string[] args)
  2.         {
  3.             Employee employee = new Employee()
  4.             {
  5.                 Id = 1,
  6.                 FirstName = "Michael",
  7.                 LastName = "Stevens",
  8.                 Salary = 5000,
  9.                 Country = "Canada"
  10.             };
  11.             decimal incometax = ComputeIncomeTax
  12.             (employee, employee.Salary);
  13.             Console.WriteLine("The income tax is {0}", incometax);
  14.             Console.Read();
  15.         }

C# 8 的 tuple模式

Tuple 模式是另一种模式类型,常用于实现同一时刻对多个 input 值进行测试,下面的代码片段展示了如何使用 tuple模式。

 
 
 
 
  1. static void Main(string[] args)
  2.         {
  3.             static string GetLanguageNames(string team1, string team2) => (team1, team2) switch
  4.             {
  5.                 ("C++", "Java") => "C++ and Java.",
  6.                 ("C#", "Java") => "C# and Java.",
  7.                 ("C++", "C#") => "C++ and C#.",
  8.                 (_, _) => "Invalid input"
  9.             };
  10.             (string, string, string, string) programmingLanguages = ("C++", "Java", "C#", "F#");
  11.             var language1 = programmingLanguages.Item1.ToString();
  12.             
  13.             var language2 = programmingLanguages.Item3.ToString();
  14.             
  15.             Console.WriteLine($"The languages selected are: {GetLanguageNames(language1, language2)}");
  16.         }

C# 8 中对 模式匹配进行了若干种增强,使得代码写起来更加易读,易维护 和 更加高效,也是这么多年程序员翘首以盼的特性之一。

译文链接:https://www.infoworld.com/article/3518431/how-to-use-pattern-matching-in-csharp-80.html

文章标题:如何在C#8中使用模式匹配
标题链接:http://www.shufengxianlan.com/qtweb/news33/31783.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联