c# - 为什么派生类不能用从原始类型派生的类型覆盖其基类中的属性?
问题描述
实际上,我想了解为什么这在 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 或其他东西)。编译器会知道这是否会发生,所以这似乎是一种非问题。
我也明白这可以通过抽象类来实现,但我特别想更好地理解为什么在非抽象类的情况下不允许这样做。
解决方案
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.
推荐阅读
- powershell - Powershell导航到特定目录
- google-analytics - 如何使用 Google Analytics API 启用广告功能?
- excel - Power Query 表达式错误:“记录”类型的值无法转换为“文本”类型
- .net-core - 如何翻译 Blazor 组件和 App.razor 中的字符串?
- python - i = self.pos[0] 说 TypeError: 'int' object is not subscriptable,我的代码的第 18 行和第 19 行
- django - 如何从列表中提取 JSON 值并以 django 模型形式呈现?
- sas - 如何在 SAS 中使用 WHERE 函数?
- hangouts-chat - 使用 Google Chat API 创建的 Bot 的 URI/超链接
- git - Rubocop:从命令行给出的列表中排除文件
- python - 使用协程和函数作为 python 中的方法保持 SOLID 和 DRY