我试图通过反复阅读维基百科条目来确定我对上述原则的理解。
撇开仍然让我感到悲伤的协变和逆变的概念,维基百科还提到超类型的不变量必须保留在子类型和历史约束或历史规则中。基于这最后两个概念,我想出了这个小例子:
class Program
{
static void Main(string[] args)
{
var fooUser = new FooUser();
var fooBase = new FooBase("Serge");
var fooDerived = new FooDerived("Serge");
fooUser.Use(fooBase); //will print "Serge"
fooUser.Use(fooDerived); //will print "New User"
Console.ReadKey();
}
}
public class FooUser
{
public void Use(IFoo foo)
{
foo.DoSomething();
Console.WriteLine(foo.Name);
}
}
public interface IFoo
{
string Name { get; }
void DoSomething();
}
public class FooBase : IFoo
{
public string Name { get; protected set; }
public FooBase(string name)
{
Name = name;
}
public virtual void DoSomething()
{
}
}
public class FooDerived : FooBase
{
public FooDerived(string name) : base(name)
{
}
public override void DoSomething()
{
Name = "New Name";
base.DoSomething();
}
}
所以我的问题是:基于上述两个概念,我是否违反了这个例子的原则?如果不是,为什么?
非常感谢您提前。