c# - 为什么在声明中隐式向上转换?

标签 c# oop casting

为什么我要在声明时隐式向上转型?我的问题来自教科书中的以下代码。

private readonly IList<Inventory> _cars = new ObservableCollection<Inventory>();

我为什么不直接这样做。

private readonly ObservableCollection<Inventory> _cars = new ObservableCollection<Inventory>();

如果我只是为了节省空间,为什么不这样做呢?

private readonly var _cars = new ObservableCollection<Inventory>();

谢谢,

最佳答案

这与节省击键无关;这是关于“最小权限”的原则。

这个:

private readonly var _cars = new ObservableCollection<Inventory>();

还有这个:

private readonly ObservableCollection<Inventory> _cars = new ObservableCollection<Inventory>();

明确声明 _cars 是可观察的。您之后编写的代码可能会依赖于此,即使它不是您的原始设计。一般来说,您希望使用最简单的接口(interface)来完成这项工作,因此如果您的代码的某些部分不需要知道某些东西是可观察的,那么静态类型变量是一个很好的做法,这样它们就可以使用不可观察的接口(interface)。

当你写的时候:

private readonly IList<Inventory> _cars = new ObservableCollection<Inventory>();

你明确表示你不想编写依赖于可观察的 _cars 的代码,如果你这样做,编译器会出错并向你尖叫,这很好。

关于c# - 为什么在声明中隐式向上转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62413961/

相关文章:

java - 如何在不创建子类和/或继承类的情况下从另一个类调用对象的方法?

c# - 我应该多积极地进行子类化以保持 DRY?

java - 使用 <?> 参数调用通用 Java 函数

Java:通用类型转换中(缺乏)错误

c# - 在 Metro 中等待一个线程完成

c# - 错误: exception of type 'System.NullReferenceException' occurred in exe

c# - .NET 随机程序集在磁盘上被修改

c++ - 哪种设计更好 : provide direct access to an owned object or give owning object forwarding methods to the owned object?

ios - 如何将 `Int8?` 转换为 `Int?` ?

c# - Asp GridView 在整行上触发 Click 事件