C# 面向对象的三大特性
https://blog.csdn.net/yiyelanxin/article/details/94388986#封装
目录
C# 面向对象的三大特性分别是封装、继承、多态,下面将帮助您更深一步了解并运用这三大特性。
一、封装
封装 被定义为"把一个或多个项目封闭在一个物理的或者逻辑的包中"。在面向对象程序设计方法论中,封装是为了防止对实现细节的访问。
抽象和封装是面向对象程序设计的相关特性。抽象允许相关信息可视化,封装则使开发者实现所需级别的抽象。
C# 封装根据具体的需要,设置使用者的访问权限,并通过 访问修饰符 来实现。
一个 访问修饰符 定义了一个类成员的范围和可见性。C# 支持的访问修饰符如下所示:
- public:所有对象都可以访问;
- private:对象本身在对象内部可以访问;
- protected:只有该类对象及其子类对象可以访问
- internal:同一个程序集的对象可以访问(即带有 internal 访问修饰符的任何成员可以被定义在该成员所定义的应用程序内的任何类或方法访问);
- protected internal:访问限于当前程序集或派生自包含类的类型。(访问修饰符允许在本类,派生类或者包含该类的程序集中访问。这也被用于实现继承。)
internal示例:
- using System;
-  
- namespace RectangleApplication
- {
-     class Rectangle
-     {
-         //成员变量
-         internal double length;
-         internal double width;
-         
-         double GetArea()
-         {
-             return length * width;
-         }
-        public void Display()
-         {
-             Console.WriteLine("长度: {0}", length);
-             Console.WriteLine("宽度: {0}", width);
-             Console.WriteLine("面积: {0}", GetArea());
-         }
-     }//end class Rectangle    
-     class ExecuteRectangle
-     {
-         static void Main(string[] args)
-         {
-             Rectangle r = new Rectangle();
-             r.length = 4.5;
-             r.width = 3.5;
-             r.Display();
-             Console.ReadLine();
-         }
-     }
- }
二、继承
继承 是面向对象程序设计中最重要的概念之一。继承允许我们根据一个类来定义另一个类,这使得创建和维护应用程序变得更容易。同时也有利于重用代码和节省开发时间。
当创建一个类时,程序员不需要完全重新编写新的数据成员和成员函数,只需要设计一个新的类,继承了已有的类的成员即可。这个已有的类被称为的基类,这个新的类被称为派生类。
继承的思想实现了 属于(IS-A) 关系。例如,哺乳动物 属于(IS-A) 动物,狗 属于(IS-A) 哺乳动物,因此狗 属于(IS-A) 动物。
基类和派生类
一个类可以派生自多个类或接口,这意味着它可以从多个基类或接口继承数据和函数。
假设,有一个基类 Shape,它的派生类是 Rectangle:
- using System;
- namespace InheritanceApplication
- {
-    class Shape 
-    {
-       public void setWidth(int w)
-       {
-          width = w;
-       }
-       public void setHeight(int h)
-       {
-          height = h;
-       }
-       protected int width;
-       protected int height;
-    }
-  
-    // 派生类
-    class Rectangle: Shape
-    {
-       public int getArea()
-       { 
-          return (width * height); 
-       }
-    }
-    
-    class RectangleTester
-    {
-       static void Main(string[] args)
-       {
-          Rectangle Rect = new Rectangle();
-  
-          Rect.setWidth(5);
-          Rect.setHeight(7);
-  
-          // 打印对象的面积
-          Console.WriteLine("总面积: {0}",  Rect.getArea());
-          Console.ReadKey();
-       }
-    }
- }
基类的初始化
派生类继承了基类的成员变量和成员方法。因此父类对象应在子类对象创建之前被创建。您可以在成员初始化列表中进行父类的初始化。
示例如下:
- using System;
- namespace RectangleApplication
- {
-    class Rectangle
-    {
-       // 成员变量
-       protected double length;
-       protected double width;
-       public Rectangle(double l, double w)
-       {
-          length = l;
-          width = w;
-       }
-       public double GetArea()
-       {
-          return length * width;
-       }
-       public void Display()
-       {
-          Console.WriteLine("长度: {0}", length);
-          Console.WriteLine("宽度: {0}", width);
-          Console.WriteLine("面积: {0}", GetArea());
-       }
-    }//end class Rectangle  
-    class Tabletop : Rectangle
-    {
-       private double cost;
-       public Tabletop(double l, double w) : base(l, w)
-       { }
-       public double GetCost()
-       {
-          double cost;
-          cost = GetArea() * 70;
-          return cost;
-       }
-       public void Display()
-       {
-          base.Display();
-          Console.WriteLine("成本: {0}", GetCost());
-       }
-    }
-    class ExecuteRectangle
-    {
-       static void Main(string[] args)
-       {
-          Tabletop t = new Tabletop(4.5, 7.5);
-          t.Display();
-          Console.ReadLine();
-       }
-    }
- }
C# 多重继承
多重继承指的是一个类可以同时从多个父类继承行为与特征的功能。与单一继承相对,单一继承指一个类只能继承自一个父类。
C# 不支持多重继承。但是,您可以使用接口来实现多重继承。如下:
- using System;
- namespace InheritanceApplication
- {
-    class Shape 
-    {
-       public void setWidth(int w)
-       {
-          width = w;
-       }
-       public void setHeight(int h)
-       {
-          height = h;
-       }
-       protected int width;
-       protected int height;
-    }
-  
-    // 基类 PaintCost
-    public interface PaintCost 
-    {
-       int getCost(int area);
-    }
-    // 派生类
-    class Rectangle : Shape, PaintCost
-    {
-       public int getArea()
-       {
-          return (width * height);
-       }
-       public int getCost(int area)
-       {
-          return area * 70;
-       }
-    }
-    class RectangleTester
-    {
-       static void Main(string[] args)
-       {
-          Rectangle Rect = new Rectangle();
-          int area;
-          Rect.setWidth(5);
-          Rect.setHeight(7);
-          area = Rect.getArea();
-          // 打印对象的面积
-          Console.WriteLine("总面积: {0}",  Rect.getArea());
-          Console.WriteLine("油漆总成本: ${0}" , Rect.getCost(area));
-          Console.ReadKey();
-       }
-    }
- }
三、多态
多态 是同一个行为具有多个不同表现形式或形态的能力。
多态性意味着有多重形式。在面向对象编程范式中,多态性往往表现为"一个接口,多个功能"。
多态性可以是静态的或动态的。在静态多态性中,函数的响应是在编译时发生的。在动态多态性中,函数的响应是在运行时发生的。
在 C# 中,每个类型都是多态的,因为包括用户定义类型在内的所有类型都继承自 Object。
多态就是同一个接口,使用不同的实例而执行不同操作。
现实中,比如我们按下 F1 键这个动作:
- 如果当前在 Flash 界面下弹出的就是 AS 3 的帮助文档;
- 如果当前在 Word 下弹出的就是 Word 帮助;
- 在 Windows 下弹出的就是 Windows 帮助和支持。
同一个事件发生在不同的对象上会产生不同的结果。
1、静态多态性
在编译时,函数和对象的连接机制被称为早期绑定,也被称为静态绑定。C# 提供了两种技术来实现静态多态性。分别为:
- 函数重载
- 运算符重载
函数重载
您可以在同一个范围内对相同的函数名有多个定义。函数的定义必须彼此不同,可以是参数列表中的参数类型不同,也可以是参数个数不同。不能重载只有返回类型不同的函数声明。
运算符重载
您可以重定义或重载 C# 中内置的运算符。因此,程序员也可以使用用户自定义类型的运算符。重载运算符是具有特殊名称的函数,是通过关键字 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;
- }
上面的函数为用户自定义的类 Box 实现了加法运算符(+)。它把两个 Box 对象的属性相加,并返回相加后的 Box 对象。
运算符重载的完整实现:
- using System;
-  
- namespace OperatorOvlApplication
- {
-    class Box
-    {
-       private double length;      // 长度
-       private double breadth;     // 宽度
-       private double height;      // 高度
-  
-       public double getVolume()
-       {
-          return length * breadth * height;
-       }
-       public void setLength( double len )
-       {
-          length = len;
-       }
-  
-       public void setBreadth( double bre )
-       {
-          breadth = bre;
-       }
-  
-       public void setHeight( double hei )
-       {
-          height = hei;
-       }
-       // 重载 + 运算符来把两个 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;
-       }
-  
-    }
-  
-    class Tester
-    {
-       static void Main(string[] args)
-       {
-          Box Box1 = new Box();         // 声明 Box1,类型为 Box
-          Box Box2 = new Box();         // 声明 Box2,类型为 Box
-          Box Box3 = new Box();         // 声明 Box3,类型为 Box
-          double volume = 0.0;          // 体积
-  
-          // Box1 详述
-          Box1.setLength(6.0);
-          Box1.setBreadth(7.0);
-          Box1.setHeight(5.0);
-  
-          // Box2 详述
-          Box2.setLength(12.0);
-          Box2.setBreadth(13.0);
-          Box2.setHeight(10.0);
-  
-          // Box1 的体积
-          volume = Box1.getVolume();
-          Console.WriteLine("Box1 的体积: {0}", volume);
-  
-          // Box2 的体积
-          volume = Box2.getVolume();
-          Console.WriteLine("Box2 的体积: {0}", volume);
-  
-          // 把两个对象相加
-          Box3 = Box1 + Box2;
-  
-          // Box3 的体积
-          volume = Box3.getVolume();
-          Console.WriteLine("Box3 的体积: {0}", volume);
-          Console.ReadKey();
-       }
-    }
- }
可重载和不可重载运算符
下表描述了 C# 中运算符重载的能力:
| 运算符 | 描述 | 
|---|---|
| +(正), -(负), !, ~(位非), ++, -- | 这些一元运算符只有一个操作数,且可以被重载。 | 
| +, -, *, /, % | 这些二元运算符带有两个操作数,且可以被重载。 | 
| ==, !=, <, >, <=, >= | 这些比较运算符可以被重载。 | 
| &&, || | 这些条件逻辑运算符不能被直接重载。 | 
| +=, -=, *=, /=, %= | 这些赋值运算符不能被重载。 | 
| =, ., ?:, ->, new, is, sizeof, typeof | 这些运算符不能被重载。 | 
2、动态多态性
C# 允许使用关键字 abstract 创建抽象类,用于提供接口的部分类的实现。当一个派生类继承自该抽象类时,实现即完成。抽象类包含抽象方法,抽象方法可被派生类实现。派生类具有更专业的功能。
请注意,下面是有关抽象类的一些规则:
- 不能创建一个抽象类的实例。
- 不能在一个抽象类外部声明一个抽象方法。
- 通过在类定义前面放置关键字 sealed,可以将类声明为密封类。当一个类被声明为 sealed 时,它不能被继承。抽象类不能被声明为 sealed。
抽象类示例:
- using System;
- namespace PolymorphismApplication
- {
-    abstract class Shape
-    {
-        abstract public 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); 
-       }
-    }
-  
-    class RectangleTester
-    {
-       static void Main(string[] args)
-       {
-          Rectangle r = new Rectangle(10, 7);
-          double a = r.area();
-          Console.WriteLine("面积: {0}",a);
-          Console.ReadKey();
-       }
-    }
- }
当有一个定义在类中的函数需要在继承类中实现时,可以使用虚方法。
- 虚方法是使用关键字 virtual 声明的。
- 虚方法可以在不同的继承类中有不同的实现。
- 对虚方法的调用是在运行时发生的。
- 动态多态性是通过 抽象类 和 虚方法 实现的。
以下实例创建了 Shape 基类,并创建派生类 Circle、 Rectangle、Triangle, Shape 类提供一个名为 Draw 的虚拟方法,在每个派生类中重写该方法以绘制该类的指定形状。
示例:
- using System;
- using System.Collections.Generic;
-  
- public class Shape
- {
-     public int X { get; private set; }
-     public int Y { get; private set; }
-     public int Height { get; set; }
-     public int Width { get; set; }
-    
-     // 虚方法
-     public virtual void Draw()
-     {
-         Console.WriteLine("执行基类的画图任务");
-     }
- }
-  
- class Circle : Shape
- {
-     public override void Draw()
-     {
-         Console.WriteLine("画一个圆形");
-         base.Draw();
-     }
- }
- class Rectangle : Shape
- {
-     public override void Draw()
-     {
-         Console.WriteLine("画一个长方形");
-         base.Draw();
-     }
- }
- class Triangle : Shape
- {
-     public override void Draw()
-     {
-         Console.WriteLine("画一个三角形");
-         base.Draw();
-     }
- }
-  
- class Program
- {
-     static void Main(string[] args)
-     {
-         // 创建一个 List<Shape> 对象,并向该对象添加 Circle、Triangle 和 Rectangle
-         var shapes = new List<Shape>
-         {
-             new Rectangle(),
-             new Triangle(),
-             new Circle()
-         };
-  
-         // 使用 foreach 循环对该列表的派生类进行循环访问,并对其中的每个 Shape 对象调用 Draw 方法 
-         foreach (var shape in shapes)
-         {
-             shape.Draw();
-         }
-  
-         Console.WriteLine("按下任意键退出。");
-         Console.ReadKey();
-     }
-  
- }
下面的程序演示通过虚方法 area() 来计算不同形状图像的面积:
- using System;
- namespace PolymorphismApplication
- {
-    class Shape 
-    {
-       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 ()
-       {
-          Console.WriteLine("Rectangle 类的面积:");
-          return (width * height); 
-       }
-    }
-    class Triangle: Shape
-    {
-       public Triangle(int a = 0, int b = 0): base(a, b)
-       {
-       
-       }
-       public override int area()
-       {
-          Console.WriteLine("Triangle 类的面积:");
-          return (width * height / 2); 
-       }
-    }
-    class Caller
-    {
-       public void CallArea(Shape sh)
-       {
-          int a;
-          a = sh.area();
-          Console.WriteLine("面积: {0}", a);
-       }
-    }  
-    class Tester
-    {
-       
-       static void Main(string[] args)
-       {
-          Caller c = new Caller();
-          Rectangle r = new Rectangle(10, 7);
-          Triangle t = new Triangle(10, 5);
-          c.CallArea(r);
-          c.CallArea(t);
-          Console.ReadKey();
-       }
-    }
- }
 
                     
                    
                 
                    
                 

 
         
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号