Casting between two types derived from the (same) interface

前端 未结 9 2032
南方客
南方客 2020-12-20 12:55

I have an interface and two types that derive from it.

However, I cannot do the following:

B objectB = (B) objectA

Where B derives

9条回答
  •  春和景丽
    2020-12-20 13:42

    The fact that both types implement the same interface (or have the same base-type, for that matter) does not make them interchangeable; an A is always an A, and a B is always a B. In an inheritance chain, an object can be cast as itself or any parent type. You have:

    A : ISomeInterface
    B : ISomeInterface
    

    which lets you cast an A as A or ISomeInterface, and a B as B or ISomeInterface

    or (depending on your meaning of "derived from")

    SomeBaseType
     > A
     > B
    

    which lets you cast an A as A or SomeBaseType, and a B as B or SomeBaseType

    (plus object, in each case)

提交回复
热议问题