扩展方法略好于帮助方法

如果针对一个类型实例的代码片段经常被用到,我们可能会想到把之封装成帮助方法。如下是一段针对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.mzph.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…