19-C#笔记-多态性

# 静态多态性

---

## 1 函数重载

和C++一样。

---

## 2 运算符重载

public

static 

operator

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;
}

 

不是所有的运算符都可以被重载。

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

运算符只能采用值参数,不能采用 ref 或 out 参数。

C# 要求成对重载比较运算符。如果重载了==,则也必须重载!=,否则产生编译错误。同时,比较运算符必须返回bool类型的值,这是与其他算术运算符的根本区别。

C# 不允许重载=运算符,但如果重载例如+运算符,编译器会自动使用+运算符的重载来执行+=运算符的操作。

---

# 动态多态性

---

## 3 派生/继承

abstract 抽象类,父类、基类;

* 抽象类和普通类都可以被继承,但是抽象类不能实例化;

sealed 封闭类,不能被继承;

virtual 虚方法,虚函数;

override 子类重载虚函数的时候,需要这个关键字。

   abstract class Shape // abstract 可以没有,abstract表示不能实例化
   {
      protected int width, height;
      public Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      public virtual int area() // 虚函数
      {
         Console.WriteLine("父类的面积:");
         return 0;
      }
   }
   class Rectangle: Shape
   {
      public Rectangle( int a=0, int b=0): base(a, b)
      {

      }
      public override int area () // 重载虚函数 override
      {
         Console.WriteLine("Rectangle 类的面积:");
         return (width * height); 
      }
   }

  

---

 

参考:

http://www.runoob.com/csharp/csharp-operator-overloading.html

http://www.runoob.com/csharp/csharp-polymorphism.html

https://blog.csdn.net/t_twory/article/details/51543247

 

原文地址:https://www.cnblogs.com/alexYuin/p/9069292.html