C#返回类型协变和里氏代换原则

标签 c# covariance solid-principles liskov-substitution-principle

我正在尝试了解协方差和 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# 支持协变返回类型,则可以这样声明 Base2Method() 的覆盖:

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/

相关文章:

c# - 从 setwindowhookex 获取窗口标题

c# - 如何确定上传的文件是 UTF-8 还是 UTF-16?

java - 如何使用泛型在 Java 中将 List<?> 转换为 List<T>?

c# - 当您知道要分配的字段名称时,是否可以将数组分配给未知类型的数组?

c# - 命令模式用于返回数据

c# - 即使使用 ConfigureAwait(false),在 WebAPI 中同步调用异步方法也会死锁

c# - 在 C# 中使用 SQLite 的 Dapper 查询抛出错误 "' 必须为以下参数添加值”

scala - 为协变集合添加 `to[Col[_]]` 方法

java - 在旧代码中使用 SOLID 原则实现新功能

oop - 违反了哪些 SOLID 原则?