使用案例:我正在使用数据模板将视图与ViewModel进行匹配。数据模板通过检查所提供的具体类型的最派生类型来工作,并且它们不查看它提供的接口,所以我必须在没有接口的情况下执行此操作。这是违反Liskov替代原则吗?如果是这样,我该怎么办?
我在这里简化了这个例子,而忽略了NotifyPropertyChanged等,但在现实世界中,一个View将绑定到Text属性。为了简单起见,假设带有TextBlock的视图将绑定到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?如果是这样,有什么更好的方法来做到这一点?
http://en.wikipedia.org/wiki/Liskov_substitution_principle(对于那些还没有喝过咖啡的人) – 2010-10-22 12:41:20
@SomeMiscGuy:对不起,添加链接:) – 2010-10-22 12:42:49
顺便说一下,有可能解决一个基于数据模板在实现接口的类上使用DataTemplateSelector。这对我来说效果很好:http://complexdatatemplates.codeplex.com/ – 2010-10-22 13:11:36