gpt4 book ai didi

c# - 重写方法是违反 LSP 的唯一方法吗

转载 作者:行者123 更新时间:2023-12-02 20:09:57 25 4
gpt4 key购买 nike

我正在寻找代码中的标志,以表明可能违反里氏替换原则。首先,我创建了一个简单的类和另一个继承它的类:

public class Adder
{
public virtual int Add(int operand1, int operand2)
{
return operand1 + operand2;
}
}

public class AdvancedAdder : Adder
{
}

然后我创建了一个检测 LSP 违规的 UnitTest:

public abstract class AdderUnitTestsBase
{
protected static Adder Adder;

[DataTestMethod]
[DataRow(2, 2, 4)]
[DataRow(-1, 2, 1)]
[DataRow(2, -3, -1)]
[DataRow(0, 0, 0)]
public void Add_ReturnsCorrectResult(
int operand1, int operand2, int result)
{
Assert.AreEqual(result, Adder.Add(operand1, operand2));
}
}


[TestClass]
public class AdderUnitTests : AdderUnitTestsBase
{
[ClassInitialize]
public static void ClassInit(TestContext context)
{
Adder = new Adder();
}
}

[TestClass]
public class AdvancedAdderUnitTests : AdderUnitTestsBase
{
[ClassInitialize]
public static void ClassInit(TestContext context)
{
Adder = new AdvancedAdder();
}
}

然后我尝试了不同的方法,例如更改参数类型或更改参数数量:

public class AdvancedAdder : Adder
{
public int Add(int operand1, int operand2, int operand3)
{
return operand1 + operand2 + operand3;
}

public uint Add(uint operand1, uint operand2)
{
return operand1 + operand2;
}
}

它没有违反 LSP,因为方法具有不同的签名。它只是扩展了功能。唯一有效的是使用“override”关键字:

public class AdvancedAdder : Adder
{
public override int Add(int operand1, int operand2)
{
return operand1 - operand2;
}
}

看起来如果我在 C# 中避免“覆盖”,我就不需要担心可能违反里氏替换原则。你认为这是正确的吗?

最佳答案

重写只是重新定义方法的一种技术解决方案。 LSP 更多的是关于语义而不是技术。

It looks like if I avoid "override" in C# I don't need to worry about possible Liskov's Substitution Principle violation.

也许您的意思是多态性,因为覆盖只是更改对象行为(动态绑定(bind))的一种方法。您还可以将 new 用于非virtual 方法(静态绑定(bind))。您甚至可以使用检查(作为反射的特殊情况)并基于此更改行为:

public void method()
{
switch (this.getType().Name)
{
case "Square":
// do the square thing
break;
case "Rectangle":
// do the rectangle thing
break;
}
}

像这样定义的方法可以很好地破坏 LSP,而无需继承或覆盖/new关键字。

它确实比简单的语法更复杂,并且更多地涉及语义(含义)。

即使是带有正方形/矩形的经典 LSP 示例也都是关于含义的。如果您认为正方形/矩形只是没有语义基础的单词,那么您对它们的行为就没有期望。因此,您没有理由认为您可以替代其中一个而无法破坏 LSP。

另一方面,继承是一种代码构造,它告诉您:

PARENT
^
|
CHILD

The child can substitute the parent because it inherits all the behavior.

关于c# - 重写方法是违反 LSP 的唯一方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53832905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com