本文介绍了C#返回类型协方差和Liskov替换原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解协方差和LSP.从这个问题中,我可以看到C#不支持返回类型协方差.但是, Liskov替换原则对返回类型施加了协方差.

I'm trying to understand Covariance and LSP. From this question I can see C# does not support return type covariance. However Liskov substitution principle imposes covariance on return type.

这是否意味着不可能在C#中应用此原理?还是我误会了什么?

Does it mean it is impossible to apply this principle in C# ? Or did I missunderstand something ?

推荐答案

C#仍可以应用Liskov替换原理.

C# can still apply the Liskov substitution principle.

考虑:

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()的替代:

If C# supported covariant return types, then the override for Method() in Base2 could be declared thusly:

public class Derived2 : Base2
{
    public override Derived1 Method()
    {
        return new Derived1();
    }
}

C#不允许这样做,您必须声明返回类型与基类中的返回类型相同,即Base1.

C# does not allow this, and you must declare the return type the same as it is in the base class, namely Base1.

但是,这样做并不违反Liskov替代原则.

However, doing so does not make it violate the Liskov substitution principle.

考虑一下:

Base2 test = new Base2();
Base1 item = test.Method();

相比:

Base2 test = new Derived2();
Base1 item = test.Method();

我们完全可以用new Derived2()替换new Base2(),没有任何问题.这符合Liskov替代原则.

We are completely able to replace new Base2() with new Derived2() with no issues. This complies with the Liskov substitution principle.

这篇关于C#返回类型协方差和Liskov替换原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 20:23