gpt4 book ai didi

dart - 在 Dart 中按类映射

转载 作者:行者123 更新时间:2023-12-04 15:14:07 25 4
gpt4 key购买 nike

我正在将一些 Java 代码移植到 Dart,它大量使用这些类型的 map :

Map<Class<? extends SomeClass>, SomeOtherClass> map = new HashMap<>();

目前,这在 dart 中似乎是不可能的。我知道有一个提议引入一级类型: http://news.dartlang.org/2012/06/proposal-for-first-class-types-in-dart.html这将介绍

class Type {
@native String toString();
String descriptor(){...} // return the simple name of the type
}

因此,在此提案得到实现之前,我创建了以下类(class):

class Type {
final String classname;
const Type(this.classname);
String descriptor() => classname;
}

我需要它的类有一个简单的获取方法

abstract Type get type();

这样我就可以使用我的 Type就像我会使用真正的 Type稍后切换,我只需要删除我的解决方法。

我的问题:在真正的 Type 之前,是否有一些快速的方法来进行这种映射(我没有看到)或者我这样做的方式是一种合理的解决方法类(class)介绍?

Dart 1.0 更新

可以这样做:

var map = new Map<Type, SomeOtherClass>();
// either
map[SomeOtherClass] = new SomeOtherClass();
// or
var instance = new SomeOtherClass();
map[instance.runtimeType] = instance;

最佳答案

更新 :此构造目前在 Dart 中不可行

Map<Class<? extends SomeClass>, SomeOtherClass>

您将不得不等待 .type/.class 找到一个优雅的解决方案(我们很多 Dartisans 都希望这能早日到来)。然而对于更简单的情况

Map<? extends SomeClass, SomeOtherClass>

你可以做

 Map<SomeClass, SomeOtherClass> aMap;

就像在 Dart 中任何扩展 的类一样SomeClass 也将是一个有效的 SomeClass .例如,如果您在选中模式下运行以下代码:

main() {
Map<Test, String> aMap = new HashMap<Test, String>();
var test = new Test("hello");
var someTest = new SomeTest("world");
var notATest = new NotATest();

aMap[test] = test.msg;
aMap[someTest] = someTest.msg;
aMap[notATest] = "this fails";
}

class Test implements Hashable {
Test(this.msg);

int hashCode() => msg.hashCode();

final String msg;
}

class SomeTest extends Test {
SomeTest(String message): super(message);
}

class NotATest implements Hashable {
int hashCode() => 1;
}

那么你会得到错误:

type 'NotATest' is not a subtype of type 'Test' of 'key'.

关于dart - 在 Dart 中按类映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11403020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com