C#的扩展方法(Extension Methods)(一)

2020-03-03  本文已影响0人  lyx2002py

扩展方法能够给直接给现存的类型”添加“方法,而不需要去继承、重编译或是修改原类型。让他们看起来就好像是原类型的实例方法。

比如System.DateTime是一个Struct结构,无法通过继承的方式生成子类,如果涉及要添加该方法的类型时,往往会选择使用静态类静态方法,如下面这个例子:

using System;

namespace LeaningBasic
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime time = DateTime.Now;
            
            //静态方法
            int daysToThisMonth = DateTimeComponent.DaysToThisMonth(time);

            //扩展方法
            int daysToThisMonth2 = time.DaysToThisMonth2();
            
            Console.WriteLine(daysToThisMonth + " " + daysToThisMonth2);
        }
    }

    public static class DateTimeComponent
    {
        public static int DaysToThisMonth(DateTime date)
        {
            return DateTime.DaysInMonth(date.Year, date.Month) - date.Day;
        }
        
        public static int DaysToThisMonth2(this DateTime date)
        {
            return DateTime.DaysInMonth(date.Year, date.Month) - date.Day;
        }
    }
}

注意,方法中的this修饰符

上一篇下一篇

猜你喜欢

热点阅读