gpt4 book ai didi

flutter - 如何从对象实例的类型实例化泛型?

转载 作者:行者123 更新时间:2023-12-03 03:03:41 43 4
gpt4 key购买 nike

这是我的代码:

class Foo {}
class MyClass extends Foo {}
class HisClass extends Foo {}
class YourClass extends Foo {}

var x = [
MyClass(),
HisClass(),
YourClass()
];

class Something<T extends Foo> {}
我想从 Something创建一个 x类的列表。我以为我应该可以这样做,但是会产生 'dynamic' doesn't extend 'Foo'. Try using a type that is or is a subclass of 'Foo'.darttype_argument_not_matching_bounds错误
List<Something> list = x.map((entry) => new Something<entry.runtimeType>())
如何使编译器对我所做的事情安全感到满意?

最佳答案

可能是这样的:

void main() async {
var x = [MyClass(), HisClass(), YourClass()];

var list = x.map(Something
.builder); // Instance of 'Something<MyClass>', Instance of 'Something<HisClass>', Instance of 'Something<YourClass>'

print(list);
}

class Foo {}

class MyClass extends Foo {}

class HisClass extends Foo {}

class YourClass extends Foo {}

class Something<T extends Foo> {
Something();

static Something<Foo> builder(Foo item) {
switch (item.runtimeType) {
case (MyClass):
return Something<MyClass>();
case (HisClass):
return Something<HisClass>();
case (YourClass):
return Something<YourClass>();
}

return Something<Foo>();
}
}

关于flutter - 如何从对象实例的类型实例化泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63438058/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com