gpt4 book ai didi

dart - 如何捕获泛型约束的泛型类型?

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

考虑以下泛型类:

class Foo<T extends Bar<dynamic>> {}

如何在编译时获取 Bar 的泛型参数?

我希望下面的代码打印int,但它打印dynamic:

class Bar<T> {}

class Foo<T extends Bar<dynamic>> {
Foo(this.value) {
_debugBarType(value);
}

final T value;

void _debugBarType<A>(Bar<A> value) {
print(A);
}
}

void main() {
Foo<Bar<int>>(Bar());
}

我知道我能做到:

class Foo<A, Bar<A>> {}

但我想使用单个泛型参数而不是两个来定义 Foo 类。

最佳答案

目前在任何类上都不可能做到这一点。

目前 Dart 上有一个待处理的功能请求来支持这样的用例:https://github.com/dart-lang/language/issues/620

值得注意的是,如果您可以在相关类上添加方法,则有一种解决方法。

例如,假设您有一个泛型类 Model<T> :

class Model<T> {
T value;
}

然后你可以像这样添加一个“捕获”方法:

class Model<T> {
T value;

R capture<T>(void cb<P>(P value)) => cb<T>(value);
}

然后你可以这样写:

void someFunction<T extends Model<dynamic>>(T model) {
model.capture(<P>(value) {
// `P` will be the captured type instead of `dynamic`
});
}

关于dart - 如何捕获泛型约束的泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56579619/

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