美文网首页
C#的扩展方法(Extension Methods)(一)

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

作者: lyx2002py | 来源:发表于2020-03-03 00:30 被阅读0次

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

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

    相关文章

      网友评论

          本文标题:C#的扩展方法(Extension Methods)(一)

          本文链接:https://www.haomeiwen.com/subject/swvnkhtx.html