【问题标题】:Dart - Get current type of the classDart - 获取当前类的类型
【发布时间】:2021-07-02 22:33:33
【问题描述】:

我想创建一个类并引用“当前类的类型”。

例如,在这个小 sn-p 中,我创建了一个类 A,其中包含 .child。

正如它所写,.child (A?) 的类型是“硬编码”,我的意思是,如果我创建扩展 A、@987654329 的 B @ 将是 A? 类型。我希望它自动成为B? “因为当前类是B”。

class A {
  A? child;
}

class B extends A {
  
}

B? f(B b) {
  return b.child;
}

因为它现在,它显示错误

line 10 • A value of type 'A?' can't be returned from the function 'f' because it has a return type of 'B?'. 

有没有办法做我想做的事?如果是,怎么做?

【问题讨论】:

    标签: class dart extends


    【解决方案1】:

    一种方法是使用泛型并从 C++ 中借用 curiously-recurring template pattern,以便基类知道派生类的类型:

    class A<Derived extends A<Derived>> {
      Derived? child;
    }
    
    class B extends A<B> {
    }
    

    或者,您可以将A 设为抽象类并让B 覆盖child:

    abstract class A {
      A? get child;
    }
    
    class B extends A {
      @override
      B? child;
    }
    

    如果A 需要child 的setter,您可以使用covariant 来安抚静态分析并允许在运行时检查setter 的值:

    abstract class A {
      A? get child;
      set child(A? value);
    }
    
    class B extends A {
      @override
      covariant B? child;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 2016-10-17
      • 2022-01-26
      • 2012-08-05
      • 1970-01-01
      • 2012-07-13
      • 2016-04-08
      相关资源
      最近更新 更多