作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑以下泛型类:
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/
我是一名优秀的程序员,十分优秀!