C#中的模式匹配通過is表達(dá)式和switch表達(dá)式使條件邏輯更簡潔、更具表現(xiàn)力。1. 使用is表達(dá)式可進(jìn)行簡潔的類型檢查,如if (obj is string s),同時(shí)提取值;2. 可結(jié)合邏輯模式(and、or、not)簡化條件判斷,如value is > 0 and
Pattern matching in C#—especially with is
expressions and switch
expressions—makes conditional logic cleaner, more expressive, and often easier to maintain. It helps you write code that’s focused on the shape or structure of data rather than just its type or value.
Using is
expressions for concise type checks
Before C# 7, checking types usually meant using a combination of is
followed by an explicit cast:
if (obj is string) { string s = (string)obj; // do something with s }
With pattern matching, you can simplify this into a single line:
if (obj is string s) { // use s directly }
This approach reduces boilerplate and keeps your logic tight. You're not just checking a condition—you’re extracting usable values at the same time.
Another handy use is combining it with logical patterns (and
, or
, not
). For example:
if (value is > 0 and < 10) { // value is between 1 and 9 }
Or filtering out nulls:
if (input is not null) { // proceed safely }
These make simple conditions easier to read and write without extra nesting or casting.
Switch expressions for clean multi-case logic
Traditional switch
statements were limited—they mostly worked with primitive types like int
or string
, and required verbose syntax with case
, break
, and so on.
C# 8 introduced switch expressions, which are much more flexible and compact. They work with any type and support pattern matching:
var result = shape switch { Circle c => $"Circle with radius {c.Radius}", Rectangle r => $"Rectangle {r.Width}x{r.Height}", _ => "Unknown shape" };
Here, each case matches both the type and optionally extracts properties. The _
acts as a default fallback.
This style removes a lot of ceremony from the older switch
syntax. It also enforces exhaustiveness, meaning the compiler will warn you if you miss a possible case.
You can even match based on property values:
var message = person switch { { Age: < 18 } => "Minor", { Age: >= 65 } => "Senior", _ => "Adult" };
This makes complex conditional logic feel more declarative and less procedural.
Where pattern matching really shines
Pattern matching becomes especially useful when dealing with nested or hierarchical data structures. For example, in domain models where different types behave differently, pattern matching lets you inspect and respond to those differences clearly.
It's also great in LINQ queries or filtering operations where you want to extract or transform data based on its structure:
var adults = people.Where(p => p is { Age: >= 18 });
That one-liner filters out only adults, using property pattern matching.
In recursive data structures like trees or expressions, pattern matching can help you deconstruct nodes cleanly and handle each case without deep nesting.
So, yeah, pattern matching in C# doesn't just save keystrokes—it improves readability, reduces error-prone casting, and gives you a clearer way to express intent. Once you get used to writing things like is string s
or using switch expressions with rich patterns, going back feels clunky.
以上是C#中的模式匹配(例如表達(dá)式,開關(guān)表達(dá)式)如何簡化條件邏輯?的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

自定義特性(CustomAttributes)是C#中用於向代碼元素附加元數(shù)據(jù)的機(jī)制,其核心作用是通過繼承System.Attribute類來定義,並在運(yùn)行時(shí)通過反射讀取,實(shí)現(xiàn)如日誌記錄、權(quán)限控制等功能。具體包括:1.CustomAttributes是聲明性信息,以特性類形式存在,常用於標(biāo)記類、方法等;2.創(chuàng)建時(shí)需定義繼承自Attribute的類,並用AttributeUsage指定應(yīng)用目標(biāo);3.應(yīng)用後可通過反射獲取特性信息,例如使用Attribute.GetCustomAttribute();

在C#中設(shè)計(jì)不可變對象和數(shù)據(jù)結(jié)構(gòu)的核心是確保對象創(chuàng)建後狀態(tài)不可修改,從而提升線程安全性和減少狀態(tài)變化導(dǎo)致的bug。 1.使用readonly字段並配合構(gòu)造函數(shù)初始化,確保字段僅在構(gòu)造時(shí)賦值,如Person類所示;2.對集合類型進(jìn)行封裝,使用ReadOnlyCollection或ImmutableList等不可變集合接口,防止外部修改內(nèi)部集合;3.使用record簡化不可變模型定義,默認(rèn)生成只讀屬性和構(gòu)造函數(shù),適合數(shù)據(jù)建模;4.創(chuàng)建不可變集合操作時(shí)推薦使用System.Collections.Imm

在ASP.NETCore中創(chuàng)建自定義中間件,可通過編寫類並註冊實(shí)現(xiàn)。 1.創(chuàng)建包含InvokeAsync方法的類,處理HttpContext和RequestDelegatenext;2.在Program.cs中使用UseMiddleware註冊。中間件適用於日誌記錄、性能監(jiān)控、異常處理等通用操作,與MVC過濾器不同,其作用於整個(gè)應(yīng)用,不依賴控制器。合理使用中間件可提升結(jié)構(gòu)靈活性,但應(yīng)避免影響性能。

寫好C#代碼的關(guān)鍵在于可維護(hù)性和可測試性。合理劃分職責(zé),遵循單一職責(zé)原則(SRP),將數(shù)據(jù)訪問、業(yè)務(wù)邏輯和請求處理分別由Repository、Service和Controller承擔(dān),提升結(jié)構(gòu)清晰度和測試效率。多用接口和依賴注入(DI),便于替換實(shí)現(xiàn)、擴(kuò)展功能和進(jìn)行模擬測試。單元測試應(yīng)隔離外部依賴,使用Mock工具驗(yàn)證邏輯,確保快速穩(wěn)定執(zhí)行。規(guī)范命名和拆分小函數(shù),提高可讀性和維護(hù)效率。堅(jiān)持結(jié)構(gòu)清晰、職責(zé)分明、測試友好的原則,能顯著提升開發(fā)效率和代碼質(zhì)量。

泛型約束用於限制類型參數(shù)以確保特定行為或繼承關(guān)係,協(xié)變則允許子類型轉(zhuǎn)換。例如,whereT:IComparable確保T可比較;協(xié)變?nèi)鏘Enumerable允許IEnumerable轉(zhuǎn)為IEnumerable,但僅限讀取,不可修改。常見約束包括class、struct、new()、基類和接口,多約束用逗號分隔;協(xié)變需用out關(guān)鍵字且只適用於接口和委託,與逆變(in關(guān)鍵字)不同。注意協(xié)變不支持類,不能隨意轉(zhuǎn)換,且約束影響靈活性。

使用LINQ時(shí)應(yīng)遵循以下要點(diǎn):1.在聲明式數(shù)據(jù)操作如過濾、轉(zhuǎn)換或聚合數(shù)據(jù)時(shí)優(yōu)先使用LINQ,避免在有副作用或性能關(guān)鍵的場景強(qiáng)制使用;2.理解延遲執(zhí)行特性,源集合修改可能導(dǎo)致意外結(jié)果,需根據(jù)需求選擇延遲或立即執(zhí)行;3.注意性能與內(nèi)存開銷,鍊式調(diào)用可能產(chǎn)生中間對象,性能敏感代碼可改用循環(huán)或Span;4.保持查詢簡潔易讀,複雜邏輯拆分為多個(gè)步驟,避免過度嵌套和混合多種操作。

C#中async和await的常見問題包括:1.錯(cuò)誤使用.Result或.Wait()導(dǎo)致死鎖;2.忽略ConfigureAwait(false)引發(fā)上下文依賴;3.濫用asyncvoid造成控制缺失;4.串行await影響並發(fā)性能。正確做法是:1.異步方法應(yīng)一路異步到底,避免同步阻塞;2.類庫中使用ConfigureAwait(false)脫離上下文;3.僅在事件處理中使用asyncvoid;4.並發(fā)任務(wù)需先啟動再await以提高效率。理解機(jī)制並規(guī)範(fàn)使用可避免寫出實(shí)質(zhì)阻塞的異步代碼。

流暢接口是一種通過鍊式調(diào)用提升代碼可讀性和表達(dá)力的設(shè)計(jì)方式。其核心在於每個(gè)方法返回當(dāng)前對象,使多個(gè)操作能連續(xù)調(diào)用,如varresult=newStringBuilder().Append("Hello").Append("").Append("World")。實(shí)現(xiàn)時(shí)需結(jié)合擴(kuò)展方法與返回this的設(shè)計(jì)模式,例如定義FluentString類並在其方法中返回this,同時(shí)通過擴(kuò)展方法創(chuàng)建初始實(shí)例。常見應(yīng)用場景包括構(gòu)建配置器(如驗(yàn)證規(guī)則)、查
