首页 > 解决方案 > 为什么派生类不能用从原始类型派生的类型覆盖其基类中的属性?

问题描述

实际上,我想了解为什么这在 C# 中是不可能的:

class Foo{
    public Bar Property {get;set;}
}

class Boo : Foo{
    public override Baz Property {get;set;}
}

class Bar{
    //some internal stuff
}

class Baz : Bar{
    //more stuff
}

对我来说,在大多数情况下,这似乎有非常明确的行为,只要 Baz 类不隐藏 Bar 类的成员(使用 new 或其他东西)。编译器会知道这是否会发生,所以这似乎是一种非问题。

我也明白这可以通过抽象类来实现,但我特别想更好地理解为什么在非抽象类的情况下不允许这样做。

标签: c#inheritancepolymorphismoverriding

解决方案


Imagine someone uses your code:

Foo f = new Boo();

As the reference is of type Foo we can only assume Property to be of type Bar. So we can also write this now:

f.Property = new Boz(); // assuming Boz also derives from Bar

which will pretty sure not be what you actually wanted.


推荐阅读