gpt4 book ai didi

c# - Liskov 替换原则、前提条件和抽象方法

转载 作者:太空狗 更新时间:2023-10-30 01:31:31 25 4
gpt4 key购买 nike

Liskov 替换原则 (LSP) 说:

Preconditions cannot be strengthened in a subtype.

在 C# 中,我可以如下违反整个原则:

public class A 
{
public virtual void DoStuff(string text)
{
Contract.Requires(!string.IsNullOrEmpty(text));
}
}

public class B : A
{
public override void DoStuff(string text)
{
Contract.Requires(!string.IsNullOrEmpty(text) && text.Length > 10);
}
}

但是,如果 A.DoStuff 是一个抽象方法会发生什么:

public class A 
{
public abstract void DoStuff(string text);
}

public class B : A
{
public override void DoStuff(string text)
{
Contract.Requires(!string.IsNullOrEmpty(text));
}
}

现在 A.DoStuff无契约(Contract)的。或者它的契约(Contract)只是所有允许的

那么,B.DoStuff 前提是否违反了 Liskov 替换原则

最佳答案

这取决于定义契约(Contract)的内容

LSP 是一种理论构造,它不依赖于特定的语言或实现,例如 C# 的“代码契约”功能。

合约可以定义为:

  • 方法名
  • 方法参数名
  • 方法注释
  • 返回类型和方法参数类型
  • “显式”契约(Contract),例如 Contract.Requires

最后两个会被编译器验证。但是,前三个也可以成为契约(Contract)的一部分!考虑以下示例:

public interface StuffContainer
{
void Add(string text);

// Removes a string that has previously been added.
void Remove(string text);
}

Remove 方法的名称和文档定义了明确的前提条件。在实现中验证要删除的字符串之前是否已添加不会违反 LSP。验证字符串至少有 5 个字符会违反 LSP。

关于c# - Liskov 替换原则、前提条件和抽象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40963811/

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