擴展方法略好于幫助方法

如果針對一個類型實例的代碼片段經常被用到,我們可能會想到把之封裝成幫助方法。如下是一段針對DateTime類型實例的一段代碼:

    class Program
    {
        static void Main(string[] args)
        {
            DateTime d = new DateTime(2001,5,18);
            switch (d.DayOfWeek)
            {
                case DayOfWeek.Saturday:
                case DayOfWeek.Sunday:
                    DoWeekendThing();
                    break;
                default:
                    DoWeekDayThing();
                    break;
            }
            Console.ReadKey();
        }
        static void DoWeekendThing()
        {
            Console.WriteLine("周末好好休息放松心情");
        }
        static void DoWeekDayThing()
        {
            Console.WriteLine("認真工作");
        }
    }
 

?

以上,把判斷是否是周末的代碼片段封裝到幫助類、幫助方法中如下:

?

    public static class DateTimeHelper
    {
        public static bool IsWeekend(DateTime dateTime)
        {
            switch (dateTime.DayOfWeek)
            {
                case DayOfWeek.Saturday:
                case DayOfWeek.Sunday:
                    return true;
                default:
                    return false;
            }
        }
    }

?

在客戶端:

?

    class Program
    {
        static void Main(string[] args)
        {
            DateTime d = new DateTime(2001,5,18);
            if (DateTimeHelper.IsWeekend(d))
            {
                DoWeekendThing();
            }
            else
            {
                DoWeekDayThing();
            }
            Console.ReadKey();
        }
        static void DoWeekendThing()
        {
            Console.WriteLine("周末好好休息放松心情");
        }
        static void DoWeekDayThing()
        {
            Console.WriteLine("認真工作");
        }
    }
 

?

用幫助類、幫助方法固然好,因為進行了很好的封裝,但每次都必須要記住擴展方法在DateTimeHelper這個擴展類中。如果System.DateTime包括IsWeekend方法會更好!

?

擴展方法是一種特殊的靜態方法,可以讓編寫的方法像現有類型的實例方法一樣被使用。

   public static class DateTimeExtensions
    {
        public static bool IsWeekend(this DateTime dateTime)
        {
            switch (dateTime.DayOfWeek)
            {
                case DayOfWeek.Saturday:
                case DayOfWeek.Sunday:
                    return true;
                default:
                    return false;   
            }
        }
    }

○ 擴展方法必須在靜態類中
○ 擴展方法必須是靜態方法
○ 擴展方法的第一個參數必須是需要被擴展的類型,而且前面必須加this關鍵字??

?

客戶端修改為:

    class Program
    {
        static void Main(string[] args)
        {
            DateTime d = new DateTime(2001,5,18);
            if (d.IsWeekend())
            {
                DoWeekendThing();
            }
            else
            {
                DoWeekDayThing();
            }
            Console.ReadKey();
        }
        static void DoWeekendThing()
        {
            Console.WriteLine("周末好好休息放松心情");
        }
        static void DoWeekDayThing()
        {
            Console.WriteLine("認真工作");
        }
    }
 

?

總結:擴展方法貌似略好于幫助方法,可以作為類型實例的方法直接被調用。

轉載于:https://www.cnblogs.com/darrenji/p/4114699.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391699.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391699.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391699.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

零元學Expression Blend 4 - Chapter 25 以Text相關功能就能簡單做出具有設計感的登入畫面...

原文:零元學Expression Blend 4 - Chapter 25 以Text相關功能就能簡單做出具有設計感的登入畫面本章將交大家如何運用Blend 4 內的Text相關功能做出有設計感的登入畫面 讓你五分鐘就能快速做出一個登入畫面 ? 本章將教大家如何運用Blend 4 內的Text相關功能做出有設計感的登入…

leetcode 395. 至少有 K 個重復字符的最長子串(滑動窗口)

給你一個字符串 s 和一個整數 k ,請你找出 s 中的最長子串, 要求該子串中的每一字符出現次數都不少于 k 。返回這一子串的長度。 示例 1: 輸入:s “aaabb”, k 3 輸出:3 解釋:最長子串為 “aaa” &…

冠狀病毒時代的負責任數據可視化

First, a little bit about me: I’m a data science grad student. I have been writing for Medium for a little while now. I’m a scorpio. I like long walks on beaches. And writing for Medium made me realize the importance of taking personal responsibility ove…

集合_java集合框架

轉載自http://blog.csdn.net/zsw101259/article/details/7570033 Java集合框架圖 簡化圖: Java平臺提供了一個全新的集合框架。“集合框架”主要由一組用來操作對象的接口組成。不同接口描述一組不同數據類型。 1、Java 2集合框架圖 ①集合接口:6個…

顯示隨機鍵盤

顯示隨機鍵盤 1 <!DOCTYPE html>2 <html lang"zh-cn">3 <head>4 <meta charset"utf-8">5 <title>7-77 課堂演示</title>6 <link rel"stylesheet" type"text/css" href"style…

數據特征分析-統計分析

一、統計分析 統計分析是對定量數據進行統計描述&#xff0c;常從集中趨勢和離中趨勢兩個方面分析。 集中趨勢&#xff1a;指一組數據向某一中心靠攏的傾向&#xff0c;核心在于尋找數據的代表值或中心值-統計平均數&#xff08;算數平均數和位置平均數&#xff09; 算術平均數…

心學 禪宗_禪宗宣言,用于有效的代碼審查

心學 禪宗by Jean-Charles Fabre通過讓查爾斯法布爾(Jean-Charles Fabre) 禪宗宣言&#xff0c;用于有效的代碼審查 (A zen manifesto for effective code reviews) When you are coding, interruptions really suck.當您編碼時&#xff0c;中斷確實很糟糕。 You are in the …

leetcode 896. 單調數列

如果數組是單調遞增或單調遞減的&#xff0c;那么它是單調的。 如果對于所有 i < j&#xff0c;A[i] < A[j]&#xff0c;那么數組 A 是單調遞增的。 如果對于所有 i < j&#xff0c;A[i]> A[j]&#xff0c;那么數組 A 是單調遞減的。 當給定的數組 A 是單調數組…

數據eda_銀行數據EDA:逐步

數據edaThis banking data was retrieved from Kaggle and there will be a breakdown on how the dataset will be handled from EDA (Exploratory Data Analysis) to Machine Learning algorithms.該銀行數據是從Kaggle檢索的&#xff0c;將詳細介紹如何將數據集從EDA(探索性…

結構型模式之組合

重新看組合/合成&#xff08;Composite&#xff09;模式&#xff0c;發現它并不像自己想象的那么簡單&#xff0c;單純從整體和部分關系的角度去理解還是不夠的&#xff0c;并且還有一些通俗的模式講解類的書&#xff0c;由于其舉的例子太過“通俗”&#xff0c;以致讓人理解產…

計算機網絡原理筆記-三次握手

三次握手協議指的是在發送數據的準備階段&#xff0c;服務器端和客戶端之間需要進行三次交互&#xff1a; 第一次握手&#xff1a;客戶端發送syn包(synj)到服務器&#xff0c;并進入SYN_SEND狀態&#xff0c;等待服務器確認&#xff1b; 第二次握手&#xff1a;服務器收到syn包…

VB2010 的隱式續行(Implicit Line Continuation)

VB2010 的隱式續行&#xff08;Implicit Line Continuation&#xff09;許多情況下,您可以讓 VB 后一行繼續前一行的語句&#xff0c;而不必使用下劃線&#xff08;_&#xff09;。下面列舉出隱式續行語法的使用情形。1、逗號“&#xff0c;”之后PublicFunctionGetUsername(By…

flutter bloc_如何在Flutter中使用Streams,BLoC和SQLite

flutter blocRecently, I’ve been working with streams and BLoCs in Flutter to retrieve and display data from an SQLite database. Admittedly, it took me a very long time to make sense of them. With that said, I’d like to go over all this in hopes you’ll w…

leetcode 303. 區域和檢索 - 數組不可變

給定一個整數數組 nums&#xff0c;求出數組從索引 i 到 j&#xff08;i ≤ j&#xff09;范圍內元素的總和&#xff0c;包含 i、j 兩點。 實現 NumArray 類&#xff1a; NumArray(int[] nums) 使用數組 nums 初始化對象 int sumRange(int i, int j) 返回數組 nums 從索引 i …

Bigmart數據集銷售預測

Note: This post is heavy on code, but yes well documented.注意&#xff1a;這篇文章講的是代碼&#xff0c;但確實有據可查。 問題描述 (The Problem Description) The data scientists at BigMart have collected 2013 sales data for 1559 products across 10 stores in…

Android控制ScrollView滑動速度

翻閱查找ScrollView的文檔并搜索了一下沒有發現直接設置的屬性和方法&#xff0c;這里通過繼承來達到這一目的。 /*** 快/慢滑動ScrollView * author農民伯伯 * */public class SlowScrollView extends ScrollView {public SlowScrollView(Context context, Att…

數據特征分析-帕累托分析

帕累托分析(貢獻度分析)&#xff1a;即二八定律 目的&#xff1a;通過二八原則尋找屬于20%的關鍵決定性因素。 隨機生成數據 df pd.DataFrame(np.random.randn(10)*10003000,index list(ABCDEFGHIJ),columns [銷量]) #避免出現負數 df.sort_values(銷量,ascending False,i…

leetcode 304. 二維區域和檢索 - 矩陣不可變(前綴和)

給定一個二維矩陣&#xff0c;計算其子矩形范圍內元素的總和&#xff0c;該子矩陣的左上角為 (row1, col1) &#xff0c;右下角為 (row2, col2) 。 上圖子矩陣左上角 (row1, col1) (2, 1) &#xff0c;右下角(row2, col2) (4, 3)&#xff0c;該子矩形內元素的總和為 8。 示…

算法訓練營 重編碼_編碼訓練營后如何找到工作

算法訓練營 重編碼by Roxy Ayaz由Roxy Ayaz 編碼訓練營后如何找到工作 (How to get a job after a coding bootcamp) Getting a tech job after a coding bootcamp is very possible, but not necessarily pain-free.在編碼訓練營之后獲得技術工作是很有可能的&#xff0c;但不…

dt決策樹_決策樹:構建DT的分步方法

dt決策樹介紹 (Introduction) Decision Trees (DTs) are a non-parametric supervised learning method used for classification and regression. The goal is to create a model that predicts the value of a target variable by learning simple decision rules inferred f…