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

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

比如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修饰符

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。