美文网首页C#修魔
C#魔帅-lesson_03-多态性

C#魔帅-lesson_03-多态性

作者: 疯帮主 | 来源:发表于2018-11-14 14:46 被阅读0次

    多态性

    多态性意味着有多重形式。在面向对象编程范式中,多态性往往表现为"一个接口,多个功能"。
    多态性可以是静态的或动态的。在静态多态性中,函数的响应是在编译时发生的。在动态多态性中,函数的响应是在运行时发生的。

    静态多态性

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

    • 函数重载
    • 运算符重载

    函数重载

    void print(int i)
          {
             Console.WriteLine("Printing int: {0}", i );
          }
    void print(double f)
          {
             Console.WriteLine("Printing float: {0}" , f);
          }
    void print(string s)
          {
             Console.WriteLine("Printing string: {0}", s);
          }
    

    运算符重载

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

    // 重载 + 运算符来把两个 Box 对象相加
    public static Box operator+ (Box b, Box c)
          {
             Box box = new Box();
             box.length = b.length + c.length;
             box.breadth = b.breadth + c.breadth;
             box.height = b.height + c.height;
             return box;
          }
    
    // 把两个 Box 对象的属性相加,并返回相加后的 Box 对象
    Box Box1 = new Box();         
    Box Box2 = new Box();  
    Box Box3 = new Box();
    Box3 = Box1 + Box2;
    

    动态多态性

    C# 允许您使用关键字 abstract 创建抽象类,用于提供接口的部分类的实现。

    // 抽象化,就是想法
    abstract class Shape
       {
          public abstract int area();
       }
    // 实现接口,画好图纸
    class Rectangle:  Shape
       {
          private int length;
          private int width;
          public Rectangle( int a=0, int b=0)
          {
             length = a;
             width = b;
          }
          public override int area ()
          { 
             Console.WriteLine("Rectangle 类的面积:");
             return (width * length); 
          }
    // 建造实物
    new Rectangle();
    

    参考文档:http://www.runoob.com/csharp/csharp-polymorphism.html

    相关文章

      网友评论

        本文标题:C#魔帅-lesson_03-多态性

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