C#多态

来源:互联网 发布:玫瑰花茶 知乎 编辑:程序博客网 时间:2024/06/07 14:59

在面向对象编程范式中,多态性往往表现为"一个接口,多个功能"。

多态性可以是静态的或动态的。

静态多态性中,函数的响应是在编译时发生的。

动态多态性中,函数的响应是在运行时发生的。

静态多态性

在编译时,函数和对象的连接机制被称为早期绑定,也被称为静态绑定。C# 提供了两种技术来实现静态多态性。分别为:

  • (1)函数重载
  • (2)运算符重载

函数重载

您可以在同一个范围内对相同的函数名有多个定义。函数的定义必须彼此不同,可以是参数列表中的参数类型不同,也可以是参数个数不同。不能重载只有返回类型不同的函数声明。

下面的实例演示了几个相同的函数 print(),用于打印不同的数据类型:

[csharp] view plain copy
  1. using System;  
  2. namespace PolymorphismApplication  
  3. {  
  4.    class Printdata  
  5.    {  
  6.       void print(int i)  
  7.       {  
  8.          Console.WriteLine("Printing int: {0}", i );  
  9.       }  
  10.   
  11.       void print(double f)  
  12.       {  
  13.          Console.WriteLine("Printing float: {0}" , f);  
  14.       }  
  15.   
  16.       void print(string s)  
  17.       {  
  18.          Console.WriteLine("Printing string: {0}", s);  
  19.       }  
  20.       static void Main(string[] args)  
  21.       {  
  22.          Printdata p = new Printdata();  
  23.          // 调用 print 来打印整数  
  24.          p.print(5);  
  25.          // 调用 print 来打印浮点数  
  26.          p.print(500.263);  
  27.          // 调用 print 来打印字符串  
  28.          p.print("Hello C++");  
  29.          Console.ReadKey();  
  30.       }  
  31.    }  
  32. }  

当上面的代码被编译和执行时,它会产生下列结果:

[csharp] view plain copy
  1. Printing int: 5  
  2. Printing float: 500.263  
  3. Printing string: Hello C++  

运算符重载

您可以重定义或重载 C# 中内置的运算符。因此,程序员也可以使用用户自定义类型的运算符。重载运算符是具有特殊名称的函数,是通过关键字 operator 后跟运算符的符号来定义的。与其他函数一样,重载运算符有返回类型和参数列表。

例如,请看下面的函数:

[csharp] view plain copy
  1. public static Box operator+ (Box b, Box c)  
  2. {  
  3.    Box box = new Box();  
  4.    box.length = b.length + c.length;  
  5.    box.breadth = b.breadth + c.breadth;  
  6.    box.height = b.height + c.height;  
  7.    return box;  
  8. }  

上面的函数为用户自定义的类 Box 实现了加法运算符(+)。它把两个 Box 对象的属性相加,并返回相加后的 Box 对象。

运算符重载的实现

下面的程序演示了完整的实现:

[csharp] view plain copy
  1. using System;  
  2.   
  3. namespace OperatorOvlApplication  
  4. {  
  5.    class Box  
  6.    {  
  7.       private double length;      // 长度  
  8.       private double breadth;     // 宽度  
  9.       private double height;      // 高度  
  10.   
  11.       public double getVolume()  
  12.       {  
  13.          return length * breadth * height;  
  14.       }  
  15.       public void setLength( double len )  
  16.       {  
  17.          length = len;  
  18.       }  
  19.   
  20.       public void setBreadth( double bre )  
  21.       {  
  22.          breadth = bre;  
  23.       }  
  24.   
  25.       public void setHeight( double hei )  
  26.       {  
  27.          height = hei;  
  28.       }  
  29.       // 重载 + 运算符来把两个 Box 对象相加  
  30.       public static Box operator+ (Box b, Box c)  
  31.       {  
  32.          Box box = new Box();  
  33.          box.length = b.length + c.length;  
  34.          box.breadth = b.breadth + c.breadth;  
  35.          box.height = b.height + c.height;  
  36.          return box;  
  37.       }  
  38.   
  39.    }  
  40.   
  41.    class Tester  
  42.    {  
  43.       static void Main(string[] args)  
  44.       {  
  45.          Box Box1 = new Box();         // 声明 Box1,类型为 Box  
  46.          Box Box2 = new Box();         // 声明 Box2,类型为 Box  
  47.          Box Box3 = new Box();         // 声明 Box3,类型为 Box  
  48.          double volume = 0.0;          // 体积  
  49.   
  50.          // Box1 详述  
  51.          Box1.setLength(6.0);  
  52.          Box1.setBreadth(7.0);  
  53.          Box1.setHeight(5.0);  
  54.   
  55.          // Box2 详述  
  56.          Box2.setLength(12.0);  
  57.          Box2.setBreadth(13.0);  
  58.          Box2.setHeight(10.0);  
  59.   
  60.          // Box1 的体积  
  61.          volume = Box1.getVolume();  
  62.          Console.WriteLine("Box1 的体积: {0}", volume);  
  63.   
  64.          // Box2 的体积  
  65.          volume = Box2.getVolume();  
  66.          Console.WriteLine("Box2 的体积: {0}", volume);  
  67.   
  68.          // 把两个对象相加  
  69.          Box3 = Box1 + Box2;  
  70.   
  71.          // Box3 的体积  
  72.          volume = Box3.getVolume();  
  73.          Console.WriteLine("Box3 的体积: {0}", volume);  
  74.          Console.ReadKey();  
  75.       }  
  76.    }  
  77. }  

当上面的代码被编译和执行时,它会产生下列结果:

[csharp] view plain copy
  1. Box1 的体积: 210  
  2. Box2 的体积: 1560  
  3. Box3 的体积: 5400  

可重载和不可重载运算符

下表描述了 C# 中运算符重载的能力:

运算符描述+, -, !, ~, ++, --这些一元运算符只有一个操作数,且可以被重载。+, -, *, /, %这些二元运算符带有两个操作数,且可以被重载。==, !=, <, >, <=, >=这些比较运算符可以被重载。&&, ||这些条件逻辑运算符不能被直接重载。+=, -=, *=, /=, %=这些赋值运算符不能被重载。=, ., ?:, ->, new, is, sizeof, typeof这些运算符不能被重载。

针对上述讨论,让我们扩展上面的实例,重载更多的运算符:

[csharp] view plain copy
  1. using System;  
  2.   
  3. namespace OperatorOvlApplication  
  4. {  
  5.     class Box  
  6.     {  
  7.        private double length;      // 长度  
  8.        private double breadth;     // 宽度  
  9.        private double height;      // 高度  
  10.         
  11.        public double getVolume()  
  12.        {  
  13.          return length * breadth * height;  
  14.        }  
  15.       public void setLength( double len )  
  16.       {  
  17.           length = len;  
  18.       }  
  19.   
  20.       public void setBreadth( double bre )  
  21.       {  
  22.           breadth = bre;  
  23.       }  
  24.   
  25.       public void setHeight( double hei )  
  26.       {  
  27.           height = hei;  
  28.       }  
  29.       // 重载 + 运算符来把两个 Box 对象相加  
  30.       public static Box operator+ (Box b, Box c)  
  31.       {  
  32.           Box box = new Box();  
  33.           box.length = b.length + c.length;  
  34.           box.breadth = b.breadth + c.breadth;  
  35.           box.height = b.height + c.height;  
  36.           return box;  
  37.       }  
  38.         
  39.       public static bool operator == (Box lhs, Box rhs)  
  40.       {  
  41.           bool status = false;  
  42.           if (lhs.length == rhs.length && lhs.height == rhs.height   
  43.              && lhs.breadth == rhs.breadth)  
  44.           {  
  45.               status = true;  
  46.           }  
  47.           return status;  
  48.       }  
  49.       public static bool operator !=(Box lhs, Box rhs)  
  50.       {  
  51.           bool status = false;  
  52.           if (lhs.length != rhs.length || lhs.height != rhs.height   
  53.               || lhs.breadth != rhs.breadth)  
  54.           {  
  55.               status = true;  
  56.           }  
  57.           return status;  
  58.       }  
  59.       public static bool operator <(Box lhs, Box rhs)  
  60.       {  
  61.           bool status = false;  
  62.           if (lhs.length < rhs.length && lhs.height   
  63.               < rhs.height && lhs.breadth < rhs.breadth)  
  64.           {  
  65.               status = true;  
  66.           }  
  67.           return status;  
  68.       }  
  69.   
  70.       public static bool operator >(Box lhs, Box rhs)  
  71.       {  
  72.           bool status = false;  
  73.           if (lhs.length > rhs.length && lhs.height   
  74.               > rhs.height && lhs.breadth > rhs.breadth)  
  75.           {  
  76.               status = true;  
  77.           }  
  78.           return status;  
  79.       }  
  80.   
  81.       public static bool operator <=(Box lhs, Box rhs)  
  82.       {  
  83.           bool status = false;  
  84.           if (lhs.length <= rhs.length && lhs.height   
  85.               <= rhs.height && lhs.breadth <= rhs.breadth)  
  86.           {  
  87.               status = true;  
  88.           }  
  89.           return status;  
  90.       }  
  91.   
  92.       public static bool operator >=(Box lhs, Box rhs)  
  93.       {  
  94.           bool status = false;  
  95.           if (lhs.length >= rhs.length && lhs.height   
  96.              >= rhs.height && lhs.breadth >= rhs.breadth)  
  97.           {  
  98.               status = true;  
  99.           }  
  100.           return status;  
  101.       }  
  102.       public override string ToString()  
  103.       {  
  104.           return String.Format("({0}, {1}, {2})", length, breadth, height);  
  105.       }  
  106.      
  107.    }  
  108.       
  109.    class Tester  
  110.    {  
  111.       static void Main(string[] args)  
  112.       {  
  113.         Box Box1 = new Box();          // 声明 Box1,类型为 Box  
  114.         Box Box2 = new Box();          // 声明 Box2,类型为 Box  
  115.         Box Box3 = new Box();          // 声明 Box3,类型为 Box  
  116.         Box Box4 = new Box();  
  117.         double volume = 0.0;   // 体积  
  118.   
  119.         // Box1 详述  
  120.         Box1.setLength(6.0);  
  121.         Box1.setBreadth(7.0);  
  122.         Box1.setHeight(5.0);  
  123.   
  124.         // Box2 详述  
  125.         Box2.setLength(12.0);  
  126.         Box2.setBreadth(13.0);  
  127.         Box2.setHeight(10.0);  
  128.   
  129.        // 使用重载的 ToString() 显示两个盒子  
  130.         Console.WriteLine("Box1: {0}", Box1.ToString());  
  131.         Console.WriteLine("Box2: {0}", Box2.ToString());  
  132.           
  133.         // Box1 的体积  
  134.         volume = Box1.getVolume();  
  135.         Console.WriteLine("Box1 的体积: {0}", volume);  
  136.   
  137.         // Box2 的体积  
  138.         volume = Box2.getVolume();  
  139.         Console.WriteLine("Box2 的体积: {0}", volume);  
  140.   
  141.         // 把两个对象相加  
  142.         Box3 = Box1 + Box2;  
  143.         Console.WriteLine("Box3: {0}", Box3.ToString());  
  144.         // Box3 的体积  
  145.         volume = Box3.getVolume();  
  146.         Console.WriteLine("Box3 的体积: {0}", volume);  
  147.   
  148.         //comparing the boxes  
  149.         if (Box1 > Box2)  
  150.           Console.WriteLine("Box1 大于 Box2");  
  151.         else  
  152.           Console.WriteLine("Box1 不大于 Box2");  
  153.         if (Box1 < Box2)  
  154.           Console.WriteLine("Box1 小于 Box2");  
  155.         else  
  156.           Console.WriteLine("Box1 不小于 Box2");  
  157.         if (Box1 >= Box2)  
  158.           Console.WriteLine("Box1 大于等于 Box2");  
  159.         else  
  160.           Console.WriteLine("Box1 不大于等于 Box2");  
  161.         if (Box1 <= Box2)  
  162.           Console.WriteLine("Box1 小于等于 Box2");  
  163.         else  
  164.           Console.WriteLine("Box1 不小于等于 Box2");  
  165.         if (Box1 != Box2)  
  166.           Console.WriteLine("Box1 不等于 Box2");  
  167.         else  
  168.           Console.WriteLine("Box1 等于 Box2");  
  169.         Box4 = Box3;  
  170.         if (Box3 == Box4)  
  171.           Console.WriteLine("Box3 等于 Box4");  
  172.         else  
  173.           Console.WriteLine("Box3 不等于 Box4");  
  174.   
  175.         Console.ReadKey();  
  176.       }  
  177.     }  
  178. }  

当上面的代码被编译和执行时,它会产生下列结果:

[csharp] view plain copy
  1. Box1: (6, 7, 5)  
  2. Box2: (12, 13, 10)  
  3. Box1 的体积: 210  
  4. Box2 的体积: 1560  
  5. Box3: (18, 20, 15)  
  6. Box3 的体积: 5400  
  7. Box1 不大于 Box2  
  8. Box1 小于 Box2  
  9. Box1 不大于等于 Box2  
  10. Box1 小于等于 Box2  
  11. Box1 不等于 Box2  
  12. Box3 等于 Box4  



动态多态性

C# 允许您使用关键字 abstract 创建抽象类,用于提供接口的部分类的实现。当一个派生类继承自该抽象类时,实现即完成。抽象类包含抽象方法,抽象方法可被派生类实现。派生类具有更专业的功能。

请注意,下面是有关抽象类的一些规则:

  • 您不能创建一个抽象类的实例。
  • 您不能在一个抽象类外部声明一个抽象方法。
  • 通过在类定义前面放置关键字 sealed,可以将类声明为密封类。当一个类被声明为 sealed 时,它不能被继承。抽象类不能被声明为 sealed。

下面的程序演示了一个抽象类:

[csharp] view plain copy
  1. using System;  
  2. namespace PolymorphismApplication  
  3. {  
  4.    abstract class Shape  
  5.    {  
  6.       public abstract int area();  
  7.    }  
  8.    class Rectangle:  Shape  
  9.    {  
  10.       private int length;  
  11.       private int width;  
  12.       public Rectangle( int a=0, int b=0)  
  13.       {  
  14.          length = a;  
  15.          width = b;  
  16.       }  
  17.       public override int area ()  
  18.       {   
  19.          Console.WriteLine("Rectangle 类的面积:");  
  20.          return (width * length);   
  21.       }  
  22.    }  
  23.   
  24.    class RectangleTester  
  25.    {  
  26.       static void Main(string[] args)  
  27.       {  
  28.          Rectangle r = new Rectangle(10, 7);  
  29.          double a = r.area();  
  30.          Console.WriteLine("面积: {0}",a);  
  31.          Console.ReadKey();  
  32.       }  
  33.    }  
  34. }  

当上面的代码被编译和执行时,它会产生下列结果:

[csharp] view plain copy
  1. Rectangle 类的面积:  
  2. 面积: 70  


当有一个定义在类中的函数需要在继承类中实现时,可以使用虚方法。虚方法是使用关键字 virtual 声明的。虚方法可以在不同的继承类中有不同的实现。对虚方法的调用是在运行时发生的。

动态多态性是通过 抽象类 和 虚方法 实现的。

下面的程序演示了这点:

[csharp] view plain copy
  1. using System;  
  2. namespace PolymorphismApplication  
  3. {  
  4.    class Shape   
  5.    {  
  6.       protected int width, height;  
  7.       public Shape( int a=0, int b=0)  
  8.       {  
  9.          width = a;  
  10.          height = b;  
  11.       }  
  12.       public virtual int area()  
  13.       {  
  14.          Console.WriteLine("父类的面积:");  
  15.          return 0;  
  16.       }  
  17.    }  
  18.    class Rectangle: Shape  
  19.    {  
  20.       public Rectangle( int a=0, int b=0): base(a, b)  
  21.       {  
  22.   
  23.       }  
  24.       public override int area ()  
  25.       {  
  26.          Console.WriteLine("Rectangle 类的面积:");  
  27.          return (width * height);   
  28.       }  
  29.    }  
  30.    class Triangle: Shape  
  31.    {  
  32.       public Triangle(int a = 0, int b = 0): base(a, b)  
  33.       {  
  34.         
  35.       }  
  36.       public override int area()  
  37.       {  
  38.          Console.WriteLine("Triangle 类的面积:");  
  39.          return (width * height / 2);   
  40.       }  
  41.    }  
  42.    class Caller  
  43.    {  
  44.       public void CallArea(Shape sh)  
  45.       {  
  46.          int a;  
  47.          a = sh.area();  
  48.          Console.WriteLine("面积: {0}", a);  
  49.       }  
  50.    }    
  51.    class Tester  
  52.    {  
  53.         
  54.       static void Main(string[] args)  
  55.       {  
  56.          Caller c = new Caller();  
  57.          Rectangle r = new Rectangle(10, 7);  
  58.          Triangle t = new Triangle(10, 5);  
  59.          c.CallArea(r);  
  60.          c.CallArea(t);  
  61.          Console.ReadKey();  
  62.       }  
  63.    }  
  64. }  

当上面的代码被编译和执行时,它会产生下列结果:

[csharp] view plain copy
  1. Rectangle 类的面积:  
  2. 面积:70  
  3. Triangle 类的面积:  
  4. 面积:25  

virtual和abstract的区别

virtual和abstract都是用来修饰父类的,通过覆盖父类的定义,让子类重新定义。

  •  1.virtual修饰的方法必须有实现(哪怕是仅仅添加一对大括号),而abstract修饰的方法一定不能实现。
  •  2.virtual可以被子类重写,而abstract必须被子类重写。
  •  3.如果类成员被abstract修饰,则该类前必须添加abstract,因为只有抽象类才可以有抽象方法。
  •  4.无法创建abstract类的实例,只能被继承无法实例化。
  • 小结

多态:一个接口多个功能。
静态多态性:编译时发生函数响应(调用);
动态多态性:运行时发生函数响应。
静态绑定(早期绑定):编译时函数和对象的连接机制。
两种技术实现静态多态性:函数重载/运算符重载
函数重载:在同一范围内对相同函数名有多个定义,可以是参数类型或参数个数的不同,但不许只有返回值类型不同。
运算符重载:可以重定义或重载 C# 中内置的运算符
两种技术实现动态多态性:抽象类/虚方法
抽象类:abstract用于接口部分类的实现(派生类继承抽象类时,实现完成)。抽象类包含抽象方法,抽象方法可被派生类实现。
虚方法:virtual用于声明虚方法,虚方法可以在不同的继承类中有不同的实现。
重载(overload):是提供了一种机制, 相同函数名通过不同的返回值类型以及参数来表来区分的机制。
重写(override):是用于重写基类的虚方法,这样在派生类中提供一个新的方法。
原创粉丝点击