模式匹配是 C# 中的一项强大功能,它允许你以更直观的方式处理各种数据形式。C# 中引入了模式匹配以支持更灵活和表达力强的代码。
以下是一些常见的模式匹配用法:
1. 类型模式匹配:
1 2 3 4 5 6 7 8 9 10
| csharpCopy codeobject data = 42;
if (data is int intValue) { Console.WriteLine($"It's an integer: {intValue}"); } else { Console.WriteLine("Not an integer"); }
|
2. Switch 表达式:
1 2 3 4 5 6 7 8 9 10
| csharpCopy codeobject value = "Hello";
string result = value switch { int intValue => "It's an integer", string stringValue => $"It's a string: {stringValue}", _ => "Unknown type" };
Console.WriteLine(result);
|
3. 属性模式:
1 2 3 4 5 6 7 8 9 10 11 12
| csharpCopy codeclass Person { public string Name { get; set; } public int Age { get; set; } }
Person person = new Person { Name = "John", Age = 30 };
if (person is { Name: "John" } johnPerson) { Console.WriteLine($"Found John, aged {johnPerson.Age}"); }
|
4. Tuple 模式:
1 2 3 4 5 6
| csharpCopy codevar tuple = (1, "Hello", 3.14);
if (tuple is (int x, string message, double z)) { Console.WriteLine($"Values: {x}, {message}, {z}"); }
|
5. Positional 模式:
1 2 3 4 5 6
| csharpCopy codevar point = (x: 3, y: 7);
if (point is (3, 7)) { Console.WriteLine("Point is at (3, 7)"); }
|
6. 类型测试和转换:
1 2 3 4 5 6 7 8 9
| csharpCopy codeif (data is int || data is string) { Console.WriteLine("Data is either int or string"); }
if (data is int intValue) { Console.WriteLine($"Converted to int: {intValue}"); }
|
模式匹配使得在处理不同数据类型和结构时更加方便,可以根据数据的形状进行更细粒度的操作。这些示例只是模式匹配的一小部分功能,实际上它可以处理更复杂的情况,例如递归模式、组合模式等。