用例:我正在使用数据模板将 View 与 ViewModel 匹配。数据模板通过检查提供的具体类型的最派生类型来工作,它们不查看它提供的接口,所以我必须在没有接口的情况下这样做。
我在这里简化了示例并省略了 NotifyPropertyChanged 等,但在现实世界中,视图将绑定到 Text 属性。为简单起见,假设带有 TextBlock 的 View 将绑定到 ReadOnlyText,而带有 TextBox 的 View 将绑定到 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?如果是这样,有什么更好的方法呢?