ExtensionOverflow:匯集優秀的C#擴充方法
擴充方法增強了C#的功能,允許在不修改現有類別原始碼的情況下新增功能。 Codeplex上的ExtensionOverflow專案邀請開發者貢獻他們最喜歡的擴充方法。
一個值得關注的貢獻:'In'方法
ExtensionOverflow專案中一個突出的貢獻是'In'擴充方法,它簡化了檢查值是否存在於陣列或清單中的任務。
<code class="language-csharp">public static bool In<T>(this T source, params T[] list) { if(source == null) throw new ArgumentNullException(nameof(source)); return list.Contains(source); }</code>
使用方法:
此方法可以取代冗長的switch-case語句或if-else分支,用來檢查集合中是否存在值。例如:
原始碼:
<code class="language-csharp">if(reallyLongIntegerVariableName == 1 || reallyLongIntegerVariableName == 6 || reallyLongIntegerVariableName == 9 || reallyLongIntegerVariableName == 11) { // 执行某些操作... }</code>
使用'In'方法後的程式碼:
<code class="language-csharp">if(reallyLongIntegerVariableName.In(1, 6, 9, 11)) { // 执行某些操作... }</code>
'In'方法簡化了程式碼,並透過消除對多個比較的需求縮短了程式碼長度。它還允許編寫更清晰、更易於維護的程式碼,從而更容易確定正在檢查的值。
以上是C#擴展方法如何簡化數組和列表中的價值檢查?的詳細內容。更多資訊請關注PHP中文網其他相關文章!