Casting between two types derived from the (same) interface

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

    You cannot cast or convert from A to B if all they share is a common interface unless you actually define your own conversion operator, assuming you control the source for one of the types, or use another provided user-defined conversion supplied by someone who does control the source. (However, such user-defined conversions would not preserve the original object. One object goes into the conversion, a different object comes out.)

    You can convert from A to Interface1, and B to Interface1. But two types simply sharing a common parent does not make those two types convertible to one another.

    A a = new A(); 
    B b = new B();
    Interface1 obj1 = a; // legal
    Interface1 obj2 = b; // legal
    B obj3 = (B)a; // not legal, a is simply not a B
    

    tobias86 put in well in a comment below, you have a cat and a dog. Both derive from Animal. But a cat just isn't a dog.


    As an expansion, you might be struggling with how and why you would use an interface. You do not use an interface to substitute an A for a B, or a B for an A. You use it to substitute either A or B for Interface1. It's the interface you expect, and the A or B you might supply. Given:

    public void DoSomething(Interface1 obj) { } // expects 
    DoSomething(new A()); // you can supply A
    

    Or

    public Interface1 GetSomething() // callers expect to get 
    {
        return new B(); // you can supply a B
    }
    

    It's the interface you are programming towards, The A and B are merely implementations. You might be thinking you can pass a B to something that expects A. The expectation possibly needs to change.

    0 讨论(0)
  • 2020-12-20 13:45

    You can only cast them to the interface type. A is not B but they are both I. this means you can take A and cast to I or B and cast to I but not B and cast to A

    0 讨论(0)
  • 2020-12-20 13:46
    1. Types do not derive from an interface. They implement an interface.
    2. The fact that both an Elephant and a Spider are Animals doesn't mean that you can convert one to the other.
    0 讨论(0)
提交回复
热议问题