c#的模式匹配通过更简洁、强大的条件判断提升代码可读性和安全性。1. 相比传统if-else,模式匹配减少冗余代码和类型转换,实现类型检查、转换与属性提取一步到位;2. 在switch表达式中使用模式匹配需确保完备性,可借助\_处理默认情况;3. 处理复杂数据结构时可嵌套使用属性模式和位置模式,深入提取信息;4. 常见错误包括未覆盖所有输入情况和模式顺序不当,应利用编译器警告和单元测试避免;5. 性能通常与if-else相当或更优,但复杂模式可能影响效率,可通过减少属性访问、缓存结果等方式优化。
C#的模式匹配本质上是一种更简洁、更强大的条件判断方式。它允许你根据数据的“形状”和“值”来进行分支,减少了冗余的代码和类型转换,让代码更易读也更安全。
C#的模式匹配通过
is
switch
类型模式 (Type Pattern): 最基础的用法,
object o is string s
o
s
true
object obj = "Hello"; if (obj is string str) { Console.WriteLine(str.Length); // 无需额外类型转换 }
常量模式 (Constant Pattern): 匹配常量值,比如
case null:
case 0:
object? value = null; switch (value) { case null: Console.WriteLine("Value is null"); break; case 0: Console.WriteLine("Value is zero"); break; default: Console.WriteLine("Value is something else"); break; }
属性模式 (Property Pattern): 直接检查对象的属性值。
public class Point { public int X { get; set; } public int Y { get; set; } } Point p = new Point { X = 10, Y = 20 }; if (p is { X: 10, Y: 20 }) { Console.WriteLine("Point is (10, 20)"); }
位置模式 (Positional Pattern): 如果类型支持解构 (deconstruction),可以使用位置模式。
public class Point { public int X { get; set; } public int Y { get; set; } public void Deconstruct(out int x, out int y) { x = X; y = Y; } } Point p = new Point { X = 5, Y = 7 }; if (p is (5, 7)) { Console.WriteLine("Point is (5, 7)"); }
var 模式 (Var Pattern): 总是匹配,并将值赋给一个新变量。 常用于
switch
default
弃元模式 (Discard Pattern): 用
_
关系模式 (Relational Pattern): 使用关系运算符(, =)进行比较。
int age = 25; string stage = age switch { < 18 => "Minor", >= 18 and < 65 => "Adult", _ => "Senior" };
逻辑模式 (Logical Pattern): 使用
and
or
not
if (obj is string s and not null) { Console.WriteLine("String is not null"); }
模式匹配更简洁、可读性更高。 传统
if-else
if (obj is Type)
switch
switch
case
switch
_
object obj = 123; string result = obj switch { int i => $"It's an integer: {i}", string s => $"It's a string: {s}", null => "It's null", _ => "It's something else" }; Console.WriteLine(result);
当处理复杂数据结构,比如嵌套的对象或集合时,可以使用嵌套的模式匹配。 结合属性模式和位置模式,可以深入到数据结构的内部,提取所需的信息。 考虑一个场景:你需要处理一个包含地址信息的对象,地址信息本身又包含城市和邮政编码。 你可以使用嵌套的模式匹配来同时检查城市和邮政编码是否符合特定的条件。
public class Address { public string City { get; set; } public string ZipCode { get; set; } } public class Person { public string Name { get; set; } public Address Address { get; set; } } Person person = new Person { Name = "Alice", Address = new Address { City = "New York", ZipCode = "10001" } }; if (person is { Address: { City: "New York", ZipCode: "10001" } }) { Console.WriteLine("Person lives in New York with zip code 10001"); }
最常见的错误是忘记处理所有可能的输入情况,导致
switch
switch
模式匹配的性能通常与传统的
if-else
以上就是C#的模式匹配(Pattern Matching)如何简化条件判断?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号