zoukankan      html  css  js  c++  java
  • C# 扩展方法

    扩展方法就是一种特殊的静态方法,不用新建派生类和重新编译原始类型。

    例:判断今天是周末还是工作日

    DateTime date = new DateTime(2015, 4, 2);
    
    switch (dateTime.DayOfWeek)
    { 
        case DayOfWeek.Saturday:
        case DayOfWeek.Sunday:
            return true;
        default:
            return false;
    }

      如果要减少代码的重复,可以写helper类

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

      调用

    if(DateTimeHelper.IsWeekend(date))
        WeekendProcessing();
    else
        WeekdayProcessing();

      使用扩展方法:

    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 关键字  这个是表明了扩展的类 还需要注意的是 必须是静态方法 而别不能与现有方法签名相同

      调用:

    DateTime date = new DateTime(2015, 4, 4);
    
    if (date.IsWeekend())
        WeekendProcessing();
    else
        WeekdayProcessing();

      把IsWeekend()方法记做了 DateTime方法的一部分 这样用的时候 和方便 也方面积累方法

      最后使用的时候别忘记进去扩展类的命名空间

  • 相关阅读:
    npm ERR! code ELIFECYCLE
    typescript react echarts map geojson
    react ts could not find a declaration file for module
    SQL SERVER 查询存储过程执行时间
    分析云优化方案
    U8 单据弃审失败 解决办法
    RCP的熔断,降级与限流(笔记五)
    RPC的优雅关闭(笔记四)
    RCP的请求路由(笔记三)
    RCP的负载均衡(笔记二)
  • 原文地址:https://www.cnblogs.com/qingducx/p/4388171.html
Copyright © 2011-2022 走看看