C#拓展方法

一、定义接口

   public interface ICalculate
    {
        int Add(int a, int b);
    }

二、定义实现接口类

  public class A : ICalculate
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }

三、接口拓展

定义静态方法和静态类,把接口当做参数传入到方法体

 public static class InterfaceExtend
    {
      public static int Sub( this ICalculate calculate, int a,int b)
        {
            return a - b;
        }

        public static int Maltiply(this ICalculate calculate, int a, int b)
        {
            return a * b;
        }

        public static int Division(this ICalculate calculate, int a, int b)
        {
            return a / b;
        }
 
    }

四、调用测试

           A a = new A();
            int res = a.Maltiply(2, 3);
            Console.WriteLine(res);

            res = a.Division(10, 2);
            Console.WriteLine(res);

            res = a.Sub(100,1);
            Console.WriteLine(res);
posted @ 2022-03-31 13:17  码农阿亮  阅读(68)  评论(0编辑  收藏  举报