首页 > 解决方案 > 将类型/类作为参数传递并访问静态属性、构造函数等

问题描述

我对飞镖还很陌生,所以我仍在努力弄清楚它的所有细微差别。根据情况,我正在尝试做的一件事是将类/类型作为参数传递给函数,以便我可以访问一些静态方法和属性。

这是一个例子:

class WithStatic {
  static final test = 'wwww';
}

void main() {
  print(WithStatic.test);
  test(WithStatic);
}


void test(dynamic cls){
  // throws error Class '_Type' has no instance getter 'test'
  print(cls.test);
}

标签: genericsdart

解决方案


这不能在 Dart 中完成。静态成员只能在实际类上直接访问,而不能在变量上访问。无论您使用类型变量 ( <T>) 还是持有Type对象的变量,都没有提供对静态成员的访问。

如果需要提供对静态成员的延迟访问,则需要传递一个函数

class WithStatic {
  static final test = 'wwww';
}

void main() {
  print(WithStatic.test);
  test(() => WithStatic.test);
}

void test(dynamic testGetter()){
  print(cls.testGetter());
}

推荐阅读