dart-从泛型扩展中提取静态方法 [英] dart - pulling static methods from generic extensions
本文介绍了dart-从泛型扩展中提取静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我在dart中实现的单例模式代码:
Here's the singleton pattern code I was implementing in dart:
void main() {
var func = new Functioner();
print("The output is: ${func.divide()(8) }");
}
class Functioner{
Function divide(){
Function letUsDivide = (int x)=>x~/4;
return letUsDivide;
}
static Functioner _mThis = null;
Functioner(){
_mThis = this;
}
static Functioner getInstance(){
if(_mThis == null)
_mThis = new Functioner();
return _mThis;
}
int divideInts(int a, int b){
return (a/b).toInt();
}
}
class MathGen<T extends Functioner>{
MathGen();
int divide(){
Functioner mVal = T;
double a = 3.5;
return T.getInstance().divideInts(3,54); #error
}
}
由于允许使用dart的仿制药它们是特定类型的子类,我认为可以使用静态字段和方法,但是我错了。如在 MathGen
类中标记为 error
的行中所述:方法getInstance()是' t为类型'Type'定义
,但是
Since dart's generics allowed making them a subclass of a particular type, I thought static fields and methods would be allowed, but I was wrong. As marked inside the MathGen
class with error
line says: the method getInstance() isn't defined for the type 'Type'
, but
- 这种语法不应该
T扩展Functioner
表示T
是否至少是
Functioner
类型? - 然后为什么
getInstance()
不可用 - 以及如何投射
T
到Functioner
? (从我发现
飞镖似乎没有显式的转换机制?)
- shouldn't this syntax
T extends Functioner
mean thatT
is atleast aFunctioner
type? - then why is
getInstance()
not available - and how do I cast
T
to aFunctioner
? (From what I have found dart seems to not have a explicit casting mechanism?)
推荐答案
您可以执行以下操作:
Functioner getInstance(){
if(_mThis == null)
_mThis = new Functioner();
return _mThis;
}
使 getInstance()
成为实例方法,然后这样称呼它:
make getInstance()
an instance method, then call it like this:
class MathGen<T extends Functioner>{
MathGen();
T widget;
int divide(){
double a = 3.5;
return widget.getInstance().divideInts(3,54);
}
}
这篇关于dart-从泛型扩展中提取静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文