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

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

  • 相关阅读:
    samdump2获取虚拟机密码
    PHP执行cmd方法若干
    Aircrack-ng学习笔记之无AP破解WiFi密码
    Python基础:extend与append的区别
    Python基础:dictionary
    UVALive 3177 长城守卫
    UVALive 3902 网络
    UVA 11520 填充正方形
    UVALive 3635 分派
    UVALive 3971 组装电脑
  • 原文地址:https://www.cnblogs.com/qingducx/p/4388171.html
Copyright © 2011-2022 走看看