• 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方法的一部分 这样用的时候 和方便 也方面积累方法

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

  • 相关阅读:
    判断闰年
    CaesarCode
    substring
    configure: error: Cannot use an external APR with the bundled APR-util
    字符串处理487-3279
    git分支管理
    git解决冲突
    git 分支的创建和切换
    nginx与php-fpm原理
    git 远程仓库与本地项目关联
  • 原文地址:https://www.cnblogs.com/qingducx/p/4388171.html
Copyright © 2020-2023  润新知