我的示例程序如下;理解Liskov替代原則
public class Animal
{
public virtual string MakeSound()
{
return "General Sound";
}
}
public class Dog : Animal
{
public override string MakeSound()
{
return "Bow..Bow..";
}
}
}
static void Main(string[] args)
{
Animal obj1 = new Animal();
Console.WriteLine("General Animal's sound id " + obj1.MakeSound());
Dog obj2 = new Dog();
Console.WriteLine("Dog Animal's sound id " + obj2.MakeSound());
//Violate LSP
Animal obj3 = new Dog();
Console.WriteLine("Animal's sound id " + obj3.MakeSound());
Console.ReadKey();
}
這裏作爲我的理解,當我們爲動物創建Dog實例(如obj3)時,我們違反了LSP。請確認我的理解。如果是的話,請告訴我如何在這種情況下實現更好的理解。我認爲我的編碼在概念上是正確的
你爲什麼認爲這會打斷LSP? (它不......) – Amit
你是否期望它在編譯時失敗或者你期待不同的輸出? –