04.C#扩展方法

1、为什么要有扩展方法?

  先思考这样一个问题,如果已有类中需要添加一个新的方法,应该如何实现呢?可能会有如下几种方法:

  (1)、有源代码情况下,直接增添一个方法 实现;

  (2)、无源代码情况下,继承该类(可继承的情况下),由子类方法实现;

             (不可继承)则通过组合的方式实现。

    但是 方法2存在一个问题,就是在使用这个方法的时候,需要一个新的类的实列来调用方法实现。那么在这种情况下如何通过原来类的实列对象进行扩展的方法调用呢?——就出现了扩展方法。

2、如何使用过扩展方法?

  (1)定义个静态类;

  (2)定义一个公共的静态方法;

  (3)扩展方法的第一个参数必须是: this TypeName 

3、举个例子看看

namespace ConsoleApp2 点击查看代码
{
    internal class Program
    {
        static void Main(string[] args)
        {
              //源代码中增加方法实现
            {
                MyMath myMath = new MyMath() { X=10,Y=20};
                // myMath.Div();
            }
            //继承方式实现
            {
                MyMathDerived myMath = new MyMathDerived() { X = 10, Y = 20 };
                myMath.Div();

            }
            //组合的方式实现
            {
                MyMathDiv myMath =new MyMathDiv() ;
                myMath.MyMath.Y = 10;
                myMath.MyMath.X = 10;
                myMath.Div();

            }
            //扩展方法实现
            {
                MyMath myMath = new MyMath() { X = 10, Y = 20 };
                myMath.Div();
            }
        }
    }
    class MyMath
    {
        private int x;

        public int X
        {
            get { return x; }
            set { x = value; }
        }

        private int y;

        public int Y
        {
            get { return y; }
            set { y = value; }
        }

        public double Add()
        {
            return X + Y;
        }
        public double Mulit()
        {
            return X * Y;
        }
        public double Sub()
        {
            return X - Y;
        }
        //源代码中增加方法实现
        //public double Div()
        //{
        //    return X / Y;
        //}

    }
    //继承方式实现
    class MyMathDerived : MyMath
    {
        public double Div()
        {
            return X / Y;
        }
    }
    //组合的方式实现
    class MyMathDiv
    {
        public MyMathDiv()
        {
            this.MyMath = new MyMath();
        }
        private MyMath myMath;

        public MyMath MyMath
        {
            get { return myMath; }
            set { myMath = value; }
        }

        public double Div()
        {
            return MyMath.X / MyMath.Y;
        }
    }
    //扩展方法实现
    static class MyMathExtent
    {
        public static double Div(this MyMath myMath)
        {
            return myMath.X / myMath.Y;
        }

    }
}

4、扩展方法的实质是什么?

posted @ 2023-09-30 21:27  猿锋博客  阅读(23)  评论(0编辑  收藏  举报