将类型/类作为参数传递并访问静态属性、构造函数等

3

我对dart还比较新,仍在努力理解它的所有细微差别。根据特定情况,我想做的一件事是将一个类/类型作为参数传递给函数,以便访问一些静态方法和属性。

以下是一个例子:

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);
}
1个回答

0

在Dart中无法完成此操作。 静态成员只能直接在实际类上访问,而不能在变量上访问。无论您使用类型变量(<T>)还是保存Type对象的变量,都无法访问静态成员。

如果您需要延迟访问静态成员,则需要传递一个函数。

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

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

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

是的,这基本上就是我现在正在做的事情,只是试图让一些代码更加DRY,不过还是谢谢你提供的信息! - Ryan Kauk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接