我不想为每种类型(在飞镖中)创建一个扩展,而是创建一个返回扩展类型的扩展。
用一个简单的例子更容易描述:
class Foo<T> {
final T value;
const Foo(this.value);
}
extension on dynamic {
Foo get foo => Foo(this);
}
final doubleTest = 0.0.foo;
final stringTest = "hello".foo;
print(doubleTest.runtimeType);
print(stringTest.runtimeType);
// Desirable output:
Foo<double>
Foo<String>
// Actual output:
Foo<dynamic>
Foo<dynamic>
我自己解决了。不多解释。很简单:
class Foo<T> {
final T value;
const Foo(this.value);
}
extension <T> on T {
Foo<T> get foo => Foo<T>(this);
}
正在运行
final doubleTest = 0.0.foo;
final stringTest = "hello".foo;
print(doubleTest.runtimeType);
print(stringTest.runtimeType);
输出:
Foo<double>
Foo<String>