首頁  >  文章  >  後端開發  >  什麼是里氏替換原則以及如何在 C# 中實現?

什麼是里氏替換原則以及如何在 C# 中實現?

PHPz
PHPz轉載
2023-09-18 19:17:04720瀏覽

什么是里氏替换原则以及如何在 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刪除