代码之家  ›  专栏  ›  技术社区  ›  creativecreatorormaybenot

强制转换子类型失败

  •  0
  • creativecreatorormaybenot  · 技术社区  · 6 年前
    class A {
      void hello() {
        print('world');
      }
    }
    
    class B extends A {
      @override
      void hello() {
        print('StackOverflow');
      }
    }
    

    (A() as B).hello(); 结果在 type 'A' is not a subtype of type 'B' in type cast

    3 回复  |  直到 6 年前
        1
  •  1
  •   Neil Locketz    6 年前

    class A {
        void hello() {
             print('world');
        }
    }
    
    
    class B extends A {
        @override
        void hello() {
            print('StackOverflow');
        }
        void hello2() {
            print('Is Great!');
        }
    }
    

    (A() as B).hello2(); B A

    class A {
        void hello() {
             print('world');
        }
    }
    
    
    class B extends A {
        @override
        void hello() {
            print('StackOverflow');
        }
    }
    
    class C extends A {
        @override
        void hello() {
            print('Hello');
        }
    }
    

    C

        2
  •  1
  •   ajawad987    6 年前

        3
  •  0
  •   lrn    6 年前

    Animal animal = Cat();
    if (something) animal = Dog();
    ...
    Cat cat = animal as Cat; // Allowed, the animal may be a cat.
    

    (A() as B) A() A B