我正在尝试了解协方差和 LSP。来自 this question我可以看到 C# 不支持返回类型协变。然而Liskov substitution principle对返回类型施加协方差。
这是否意味着不可能在 C# 中应用此原则?还是我误解了什么?
最佳答案
C# 仍然可以应用 Liskov 替换原则。
考虑:
public class Base1
{
}
public class Derived1 : Base1
{
}
public class Base2
{
public virtual Base1 Method()
{
return new Base1();
}
}
public class Derived2 : Base2
{
public override Base1 Method()
{
return new Derived1();
}
}
如果 C# 支持协变返回类型,则可以这样声明 Base2
中 Method()
的覆盖:
public class Derived2 : Base2
{
public override Derived1 Method()
{
return new Derived1();
}
}
C# 不允许这样做,您必须声明与基类中相同的返回类型,即 Base1
。
但是,这样做并不违反里氏替换原则。
考虑一下:
Base2 test = new Base2();
Base1 item = test.Method();
相比于:
Base2 test = new Derived2();
Base1 item = test.Method();
我们完全能够将 new Base2()
替换为 new Derived2()
而不会出现任何问题。这符合 Liskov 替换原则。
关于C#返回类型协变和里氏代换原则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43892239/