Casting between two types derived from the (same) interface

前端 未结 9 2043
南方客
南方客 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:31

    When casting from A to B B must be a super type for A or the runtime type of the object must be B

    that is if you have

    class A : B{}
    

    you can cast an object of compile time type A to B. You can also cast a type of B to A if the runtime type of the object is A

    in your case the two types does not share super-subtype relationship. They only share a common super type but that's not sufficient.

    As an example of why this can't work (generically) how would you have the compiler cast from Point[] to a Dictionary>? (both implement IEnumerable)

提交回复
热议问题