在 Java 中,
"Up-casting is casting to a supertype, while downcasting is casting to a subtype. Supercasting is always allowed, but subcasting involves a type check and can throw a ClassCastException."
( What is the difference between up-casting and down-casting with respect to class variable )
在 C# 中是否也总是允许向上转型?
最佳答案
是的,这是允许的,因为子类是祖先类的特殊化。
例子:
让我们考虑这样一种情况,我们有一个名为 Bird
的 class
,另一个名为 Sparrow
和第三个 Eagle
。 Sparrow
和 Eagle
继承自 Bird
。 Sparrows
与Eagles
有很大不同,但它们都是Bird
。所以,如果出于某种原因你想拥有 Bird
的 Collection
,那么你可以拥有 Eagle
和 Sparrow
同时在该Collection
中的对象,因为它们仍然是Birds
,如果只是特定 Bird
。
关于java - c# upcasting 总是被允许的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40286336/