[英]Dart: Is it possible to pass a generic type to a class as a variable?
我有一个带有通用类型的 class,我想将该类型作为变量传递。 有没有办法做到这一点?
abstract class MainType {}
class TypeA extends MainType {}
class TypeB extends MainType {}
class MyClass<T extends MainType> {}
Type getType(String key) {
if (key == 'a') return TypeA;
return TypeB;
}
MyClass constructMyObject(String key) {
final type = getType(key);
return MyClass<type>(); //<<-- This here doesn't work
}
背景是,我想从字符串中解析类型并将该类型传递给各种类。
因此,据我所知,如果没有一些解决方法,这是不可能的。
我发现的一种潜在解决方案是type_plus package 。 但我没试过。
我最终做了这样的事情:
abstract class MainType {}
class TypeA extends MainType {}
class TypeB extends MainType {}
class MyClass<T extends MainType> {}
R decodeType<R>(String? key, R Function<T extends MainType>() builder) {
if (key == 'a') return builder<TypeA>();
return builder<TypeB>();
}
MyClass constructMyObject(String key) {
// ignore: unnecessary_lambdas
return decodeType(key, <T extends MainType>() => MyClass<T>());
}
MyClass 不是 T 类型,因此您不能从中返回 MyClass object。
这是你想要的吗?
MyClass constructMyObject<T extends MainType>() {
return MyClass<T>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.