generics - 将类型/类作为参数传递并访问静态属性、构造函数等
问题描述
我对飞镖还很陌生,所以我仍在努力弄清楚它的所有细微差别。根据情况,我正在尝试做的一件事是将类/类型作为参数传递给函数,以便我可以访问一些静态方法和属性。
这是一个例子:
class WithStatic {
static final test = 'wwww';
}
void main() {
print(WithStatic.test);
test(WithStatic);
}
void test(dynamic cls){
// throws error Class '_Type' has no instance getter 'test'
print(cls.test);
}
解决方案
这不能在 Dart 中完成。静态成员只能在实际类上直接访问,而不能在变量上访问。无论您使用类型变量 ( <T>
) 还是持有Type
对象的变量,都没有提供对静态成员的访问。
如果需要提供对静态成员的延迟访问,则需要传递一个函数
class WithStatic {
static final test = 'wwww';
}
void main() {
print(WithStatic.test);
test(() => WithStatic.test);
}
void test(dynamic testGetter()){
print(cls.testGetter());
}
推荐阅读
- javascript - 在 Javascript 中转换对象格式
- r - 将 dateRangeInput 恢复为空
- java - 如何将 String 转换为从 sqlite 获取的 Uri 并在 ImageView 中设置?
- python - 如何从视觉采集卡访问数据到 opencv?
- excel - 将表单 DB 复制到 Excel 时出现 Excel 日期格式问题
- ember.js - Ember 数据:何时使用 findAll() 而不是 query()?
- django - 如何修复 Django:没有返回 HttpResponse 对象。它返回 None 而不是?
- angular - 使用“ng generate library”时,什么是 Angular“Library”?
- asp.net - Qlikview 身份验证请求被阻止,因为它是一个跨域请求
- django - 编辑现有表单的表单不保存并重定向到错误。姜戈