C# Switch 語句進(jìn)階:模式匹配詳解與實(shí)例演示
作者:架構(gòu)師老盧
模式匹配使得Switch語句更為強(qiáng)大,能夠更直觀地表達(dá)條件邏輯。不同的模式適用于不同的場(chǎng)景,根據(jù)需求選擇合適的模式,提高代碼的可讀性和可維護(hù)性。使用模式匹配可以減少代碼中的重復(fù),并提供更靈活的條件判斷方式。
在C#中,switch語句的模式匹配在C# 7.0及以上版本中引入。以下是switch語句中常見的模式及其使用方法的示例:
1. 類型模式:
優(yōu)點(diǎn): 用于檢查對(duì)象的運(yùn)行時(shí)類型,使代碼更具可讀性。
public static string GetObjectType(object obj)
{
switch (obj)
{
case int i:
return "整數(shù)類型";
case string s:
return "字符串類型";
case double d:
return "雙精度浮點(diǎn)數(shù)類型";
default:
return "其他類型";
}
}
2. 常量模式:
優(yōu)點(diǎn): 用于匹配對(duì)象是否等于某個(gè)常量值。
public static string GetDayOfWeekName(DayOfWeek day)
{
switch (day)
{
case DayOfWeek.Monday:
return "星期一";
case DayOfWeek.Tuesday:
return "星期二";
case DayOfWeek.Wednesday:
return "星期三";
case DayOfWeek.Thursday:
return "星期四";
case DayOfWeek.Friday:
return "星期五";
default:
return "其他";
}
}
3. 組合模式:
優(yōu)點(diǎn): 允許將多個(gè)模式組合在一起,形成更復(fù)雜的匹配條件。
public static string GetInfo(object obj)
{
switch (obj)
{
case int i when i > 0:
return "正整數(shù)";
case int i when i < 0:
return "負(fù)整數(shù)";
case string s when s.Length > 10:
return "字符串長(zhǎng)度大于10";
default:
return "其他";
}
}
4. 屬性模式:
優(yōu)點(diǎn): 用于匹配對(duì)象的屬性,提供更靈活的條件判斷。
public static string GetPersonInfo(object person)
{
switch (person)
{
case { Age: > 18, Name: "Alice" }:
return "成年人 Alice";
case { Age: > 18, Name: "Bob" }:
return "成年人 Bob";
case { Age: <= 18, Name: "Alice" }:
return "未成年人 Alice";
default:
return "其他";
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
5. 變量模式:
優(yōu)點(diǎn): 允許在模式中引入新的變量,提供更靈活的條件判斷。
public static string GetVariablePattern(object obj)
{
switch (obj)
{
case int i when i > 0:
return $"正整數(shù):{i}";
case int i when i < 0:
return $"負(fù)整數(shù):{i}";
case string s:
return $"字符串:{s}";
default:
return "其他";
}
}
- 模式匹配使得switch語句更為強(qiáng)大,能夠更直觀地表達(dá)條件邏輯。
- 不同的模式適用于不同的場(chǎng)景,根據(jù)需求選擇合適的模式,提高代碼的可讀性和可維護(hù)性。
- 使用模式匹配可以減少代碼中的重復(fù),并提供更靈活的條件判斷方式。
責(zé)任編輯:姜華
來源:
今日頭條