闽公网安备 35020302035485号
模式匹配 是在 C# 7 中引入的一个非常🐂的特性,你可以在任何类型上使用 模式匹配,甚至是自定义类型,而且在 C# 8 中得到了增强,引入了大量的新模式类型,这篇文章就来讨论如何在 C# 8 中使用模式匹配。
接下来看一下这些模式的相关代码及使用场景。
public class Rectangle
{
public int Length { get; set; }
public int Breadth { get; set; }
public Rectangle(int x, int y) => (Length, Breadth) = (x, y);
public void Deconstruct(out int x, out int y) => (x, y) = (Length, Breadth);
}
接下来看一下如何在 Rectangle 上使用 位置模式。 static void Main(string[] args)
{
Rectangle rectangle = new Rectangle(10, 10);
var result = rectangle switch
{
Rectangle(0, 0) => "The value of length and breadth is zero.",
Rectangle(10, 10) => "The value of length and breadth is same – this represents a square.",
Rectangle(10, 5) => "The value of length is 10, breadth is 5.",
_ => "Default."
};
Console.WriteLine(result);
}

private static void Main(string[] args)
{
Rectangle rectangle = new Rectangle(10, 10);
if (1 == 0)
{
}
if (rectangle == null)
{
goto IL_0056;
}
rectangle.Deconstruct(out int x, out int y);
string text;
if (x != 0)
{
if (x != 10)
{
goto IL_0056;
}
if (y != 5)
{
if (y != 10)
{
goto IL_0056;
}
text = "The value of length and breadth is same – this represents a square.";
}
else
{
text = "The value of length is 10, breadth is 5.";
}
}
else
{
if (y != 0)
{
goto IL_0056;
}
text = "The value of length and breadth is zero.";
}
goto IL_005e;
IL_0056:
text = "Default.";
goto IL_005e;
IL_005e:
if (1 == 0)
{
}
string result = text;
Console.WriteLine(result);
}
C# 8 的 属性模式 public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Salary { get; set; }
public string Country { get; set; }
}
下面的代码片段展示了如何利用 属性模式 实现 employee 的个人所得税计算。 public static decimal ComputeIncomeTax(Employee employee, decimal salary) => employee switch
{
{ Country: "Canada" } => (salary * 21) / 100,
{ Country: "UAE" } => 0,
{ Country: "India" } => (salary * 30) / 100,
_ => 0
};
static void Main(string[] args)
{
Employee employee = new Employee()
{
Id = 1,
FirstName = "Michael",
LastName = "Stevens",
Salary = 5000,
Country = "Canada"
};
decimal incometax = ComputeIncomeTax
(employee, employee.Salary);
Console.WriteLine("The income tax is {0}", incometax);
Console.Read();
}

static void Main(string[] args)
{
static string GetLanguageNames(string team1, string team2) => (team1, team2) switch
{
("C++", "Java") => "C++ and Java.",
("C#", "Java") => "C# and Java.",
("C++", "C#") => "C++ and C#.",
(_, _) => "Invalid input"
};
(string, string, string, string) programmingLanguages = ("C++", "Java", "C#", "F#");
var language1 = programmingLanguages.Item1.ToString();
var language2 = programmingLanguages.Item3.ToString();
Console.WriteLine($"The languages selected are: {GetLanguageNames(language1, language2)}");
}
