自学内容网 自学内容网

c#里氏替换

定义:父类对象存储子类对象。

特点:父类又不能访问子类成员。

如果需要则要显示转换。

例如:

Shape shape=new Shape();

Rectangle rectangle=new Rectangle();  //Rectangle是基类,Shape是父类。

shape=rectangle; //shape不能访问Rectangle类的成员,这是因为能否访问成员是根据变量声明决定的,shape是Shape类,决定了他只能访问自己的成员,而不能访问子类的成员。


//定义父类

 class Shape
  {  
      private string name;
      public string Name { get => name; set => name = value; }
  }

//定义子类1
  class Rectangle:Shape    

  {
      private  double length;
      private double width;

      public  double Length { get => length; set => length = value; }
      public double Width { get => width; set => width = value; }

      public Rectangle()  
      { 
   


原文地址:https://blog.csdn.net/m0_69089705/article/details/142683722

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!