我可以用存储类型做什么?

时间:2014-06-17 00:35:17

标签: dart

Dart允许类型变量:Type type = SomeType;但是出于什么目的?

例如,foo bar baz是误用:

class A {
  Type type = List;
  foo() => new type();
  type bar() {
    return new List();
  }
  type baz = new List();
}

void main() {
  Type type = String;
  var str = "Hello Dart";
  print(type == str.runtimeType);//true
  print(str is String);//true
  print(str is type); //type error.
}

我觉得这个很漂亮:

void main() {
  foo(Type t) {
    switch (t){
      case int: return 5;
      case List: return [1,2,3]; // This one gets me every time :(
      case String: return "Hello Dart!";
      default: return "default";
    }}
  print(foo(10.runtimeType)); //5
  print(foo([2,4,6].runtimeType)); //default
  print(foo("lalala".runtimeType)); //Hello Dart!
  print(foo(foo.runtimeType)); //default
}

它的唯一目的是成为runtimeType和类型匹配等方法的返回类型吗?

1 个答案:

答案 0 :(得分:1)

我认为你不能将它用于仿制药。你需要类型文字。但你可以用它来反思。

只是一个简单的例子:

import 'dart:mirrors' as mirr;

class A {
  String s;
  A(this.s);
  @override
  String toString() => s;
}

void main() {
  Type type = A;
  var str = "Hello Dart";
  mirr.ClassMirror cm = mirr.reflectType(type);
  var s = cm.newInstance(new Symbol(''), [str]).reflectee;
  print(s);
}

您还可以为不同类型的已注册工厂创建一个Map,以避免需要反射。 (未经测试)

class A {
  String s;
  int a = 0;
  int b = 0;
  int c = 0;

  A(this.s);

  A.extended(this.s, this.a, this.b, this.c);

  @override
  String toString() => '${super.toString()}: $s, $a, $b, $c';
}

void main(args) {
  Type t = A;
  registerType(t, (List args) => new A.extended(args[0], args[1], args[2], args[3]));


  ...


  var a = getInstance(t, ['hallo', 1, 2, 3]);
}

Map<Type,Function> _factories = {};

void registerType(Type t, Function factory) {
  _factories[t] = factory;
}

void getNewInstance(Type t, List args) {
  return _factories[t](args);
}