Dart:如何为任何类型创建一个扩展

问题描述 投票:0回答:1

我不想为每种类型(在飞镖中)创建一个扩展,而是创建一个返回扩展类型的扩展。

用一个简单的例子更容易描述:

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>
flutter dart extension-methods
1个回答
1
投票

我自己解决了。不多解释。很简单:

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>
© www.soinside.com 2019 - 2024. All rights reserved.