gpt4 book ai didi

c# - 这是否违反了 Liskov 替换原则,如果是,我该怎么办?

转载 作者:太空狗 更新时间:2023-10-29 23:58:31 24 4
gpt4 key购买 nike

用例:我正在使用数据模板将 View 与 ViewModel 相匹配。数据模板通过检查提供的具体类型的最派生类型来工作,它们不查看它提供的接口(interface),因此我必须在没有接口(interface)的情况下执行此操作。

我在这里简化了示例并省略了 NotifyPropertyChanged 等,但在现实世界中,View 将绑定(bind)到 Text 属性。为简单起见,假设带有 TextBlock 的 View 将绑定(bind)到 ReadOnlyText,而带有 TextBox 的 View 将绑定(bind)到 WritableText。

class ReadOnlyText
{
private string text = string.Empty;

public string Text
{
get { return text; }
set
{
OnTextSet(value);
}
}

protected virtual void OnTextSet(string value)
{
throw new InvalidOperationException("Text is readonly.");
}

protected void SetText(string value)
{
text = value;
// in reality we'd NotifyPropertyChanged in here
}
}

class WritableText : ReadOnlyText
{
protected override void OnTextSet(string value)
{
// call out to business logic here, validation, etc.
SetText(value);
}
}

通过覆盖 OnTextSet 并更改其行为,我是否违反了 LSP ?如果是这样,什么是更好的方法?

最佳答案

LSP 指出子类应该可以替代它的父类(super class)(参见 stackoverflow 问题 here)。要问自己的问题是,“可写文本是一种只读文本吗?”答案显然是否定的,事实上这些是相互排斥的。所以,是的,这段代码违反了 LSP。但是,可写文本是一种可读文本(不是只读文本)吗?答案是"is"。所以我认为答案是看看你在每种情况下试图做什么,并可能按如下方式稍微改变抽象:

class ReadableText
{
private string text = string.Empty;
public ReadableText(string value)
{
text = value;
}

public string Text
{
get { return text; }
}
}

class WriteableText : ReadableText
{
public WriteableText(string value):base(value)
{

}

public new string Text
{
set
{
OnTextSet(value);
}
get
{
return base.Text;
}
}
public void SetText(string value)
{
Text = value;
// in reality we'd NotifyPropertyChanged in here
}
public void OnTextSet(string value)
{
// call out to business logic here, validation, etc.
SetText(value);
}
}

为了清楚起见,我们在 Writeable 类的 Text 属性上使用 new 关键字来隐藏 Readable 类的 Text 属性。
来自 http://msdn.microsoft.com/en-us/library/ms173152(VS.80).aspx :当使用 new 关键字时,将调用新的类成员而不是已被替换的基类成员。这些基类成员称为隐藏成员。如果派生类的实例被强制转换为基类的实例,隐藏类成员仍然可以被调用。

关于c# - 这是否违反了 Liskov 替换原则,如果是,我该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3996819/

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