首页 >后端开发 >C#.Net教程 >什么是里氏替换原则以及如何在 C# 中实现?

什么是里氏替换原则以及如何在 C# 中实现?

PHPz
PHPz转载
2023-09-18 19:17:04738浏览

什么是里氏替换原则以及如何在 C# 中实现?

派生类型必须完全可替代其基类型。

定义:

我们应该能够将子类视为父类。本质上,这意味着所有派生类都应保留其父类的功能,并且不能替换父类提供的任何功能。

在 Liskov 替换之前

public class Ellipse {
   public double MajorAxis { get; set; }
   public double MinorAxis { get; set; }

   public virtual void SetMajorAxis(double majorAxis){
      this.MajorAxis = majorAxis;
   }
   public virtual void SetMinorAxis(double minorAxis){
      this.MajorAxis = minorAxis;
   }
   public virtual double Area() {
      return MajorAxis * MinorAxis * Math.PI;
   }
}
public class Circle : Ellipse {
   public override void SetMajorAxis(double majorAxis) {
      base.SetMajorAxis(majorAxis);
      this.MinorAxis = majorAxis; //In a cirle, each axis is identical
   }
}

public class Result {
   public void Method1() {
      Circle circle = new Circle();
      circle.SetMajorAxis(5);
      circle.SetMinorAxis(4);
      var area = circle.Area(); //5*4 = 20, but we expected 5*5 = 25
   }
}

利斯科夫替换后

internal class Program {
   private static void Main() {
   }
}
public class Ellipse {
   public double MajorAxis { get; set; }
   public double MinorAxis { get; set; }

   public virtual void SetMajorAxis(double majorAxis) {
      MajorAxis = majorAxis;
   }
   public virtual void SetMinorAxis(double minorAxis) {
      MajorAxis = minorAxis;
   }
   public virtual double Area() {
      return MajorAxis * MinorAxis * Math.PI;
   }
}
public class Circle : Ellipse {
   public override void SetMajorAxis(double majorAxis) {
      base.SetMajorAxis(majorAxis);
      this.MinorAxis = majorAxis; //In a cirle, each axis is identical
   }
   public override void SetMinorAxis(double minorAxis) {
      base.SetMinorAxis(minorAxis);
      this.MajorAxis = minorAxis;
   }
   public override double Area() {
      return base.Area();
   }
}

public class Circle1 {
   public double Radius { get; set; }
   public void SetRadius(double radius) {
      this.Radius = radius;
   }
   public double Area() {
      return this.Radius * this.Radius * Math.PI;
   }
}

以上是什么是里氏替换原则以及如何在 C# 中实现?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除