[英]Passing a class type as a variable in Dart
It is possible to pass a class type as a variable in Dart ?可以在 Dart 中将类类型作为变量传递吗?
I am trying to do something as follows:我正在尝试执行以下操作:
class Dodo
{
void hello() {
print("hello dodo");
}
}
void main() {
var a = Dodo;
var b = new a();
b.hello();
}
in python similar code would work just fine.在 python 中类似的代码可以正常工作。 In Dart I get an error at new a()
complaining that a
is not a type.在 Dart 中,我在new a()
处收到错误,抱怨a
不是类型。
Is is possible to use class objects as variables ?是否可以使用类对象作为变量? If not, what is the recommended work around ?如果没有,推荐的解决方法是什么?
ANother way to do it is by passing a closure rather than the class. 另一种方法是通过传递闭包而不是类。 Then you can avoid using mirrors. 然后你可以避免使用镜子。 eg 例如
a = () => new Dodo();
...
var dodo = a();
You can use the mirrors api: 你可以使用镜像api:
import 'dart:mirrors';
class Dodo {
void hello() {
print("hello dodo");
}
}
void main() {
var dodo = reflectClass(Dodo);
var b = dodo.newInstance(new Symbol(''), []).reflectee;
b.hello();
}
Maybe it can be written more compact, especially the new Symbol('')
expression. 也许它可以写得更紧凑,尤其是new Symbol('')
表达式。
what you can do is :你可以做的是:
const dynamic a = Dodo; // or dynamic a = Dodo;
var b = new a();
b.hello();
This works fine for me;这对我来说很好; enjoy!请享用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.