iT邦幫忙

2026 iThome 鐵人賽

DAY 19
0
自我挑戰組

學習C#續系列 第 19 篇

Day 19: 擴充方法(Extension Methods)與現代模式比對(Pattern Matching)

  • 分享至 

  • xImage
  •  

擴充方法(Extension Methods):

  • 允許在不修改原始類別原始碼、不使用繼承的前提下,向既有型別(包含 .NET 內建型別或第三方類別庫)動態「外掛」新方法。
  • 三大必備語法規則:
    • 擴充方法必須定義在靜態類別(static class)中。
    • 擴充方法本身必須宣告為靜態方法(static method)。
    • 方法的第一個參數前必須加上 this 關鍵字,用以指定要擴充的目標型別(例如 this string str)。
  • 呼叫時如同該物件自帶的實體方法,支援 IntelliSense 自動提示與方法鏈結(Method Chaining)。

現代模式比對(Pattern Matching):

  • switch 運算式(Switch Expressions):相比傳統 switch 陳述式,改用箭頭符號 => 且支援直接回傳值,預設情況以底線 _(Discard)代表 default。
  • 型別比對(Type Pattern):檢查物件是否屬於指定型別,並於符合時宣告具型別變數(例如 case Circle c:)。
  • 屬性比對(Property Pattern):直接在比對條件中使用 { 屬性名稱: 期待值 } 檢查物件屬性,免去繁瑣的 if (obj.Prop == ...) 寫法。
  • 關係與條件比對(Relational & When Clause):結合 <, >, <=, >= 進行範圍判定,或使用 when 關鍵字加上附加篩選條件。

實作範例
https://ithelp.ithome.com.tw/upload/images/20261002/20178925DCJW0tQAEy.png

https://ithelp.ithome.com.tw/upload/images/20261002/20178925FGtFhnDniO.png

https://ithelp.ithome.com.tw/upload/images/20261002/20178925udTJL5NgNp.png

https://ithelp.ithome.com.tw/upload/images/20261002/20178925uAe70i2Rqz.png


上一篇
Day 18:發行者/訂閱者模式(Publisher-Subscriber Pattern)
系列文
學習C#續 共 19 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言