gpt4 book ai didi

dart - 需要 Dart 镜像 instantiate() 函数

转载 作者:行者123 更新时间:2023-12-01 11:40:35 25 4
gpt4 key购买 nike

为了让我的生活更加理智,寻找 instantiate() 函数作为 Dart 的 mirror 库的语法糖:instantiate( class|type|instance,参数数组)

class Klass {
int i1;
Klass( int i1 ) {
this.i1 = (i1 is int) ? i1 : 0;
}
}
type ktype = Klass;
Klass kinstance = new Klass( 5 );

Klass test1 = instantiate( Klass, [5] );
Klass test2 = instantiate( ktype, [5] );
Klass test3 = instantiate( kinstance, [5] );

目前,我与 mirrors 的 90% 交互都将包含在这个函数中。目前出于纯粹的愚蠢而盲目地剪切和复制。肯定有人比我聪明已经这样做了!


这里是 instantiate( type, [constructor, positional, named] ) 所有场合:

  • 构造函数的参数、位置参数和命名参数都是可选的
  • type 可以是Type,可以是实例化类型,也可以是该类型的字符串表示
  • 构造函数:例如,new Map.from(...) - 'from' 是构造函数,'from' 或 #from
  • 位置:列表中的位置参数
  • named:在Map中命名参数,键可以是'key'或#key
dynamic instantiate( dynamic v_type, [dynamic v_constructorName, List v_positional, Map v_named] ) {  Type type =    ( _type is Type ) ? v_type    : (v_type is String ) ? str2Type( v_type )    : reflect(v_type).type.reflectedType;  Map v_named2 =    (v_named is Map) ? v_named    : (v_positional is Map) ? v_positional    : (v_constructorName is Map) ? v_constructorName    : {};  Map named = {};  v_named2.keys.forEach( (k) => named[(k is Symbol)?k:new Symbol(k)] = v_named2[k] );  List positional =    (v_positional is List) ? v_positional    : (v_constructorName is List) ? v_constructorName : [];  Symbol constructorName =    (v_constructorName is Symbol) ? v_constructorName    : (v_constructorName is String) ? Symbol(v_constructorName)    : const Symbol('');  return reflectClass(type).newInstance(constructorName, positional, named).reflectee;}

最佳答案

import 'dart:mirrors';

void main() {
Type ktype = Klass;
Klass kinstance = new Klass( 5 );
// Constructor name
var ctor = const Symbol("");

Klass test1 = instantiate(Klass, ctor, [1]);
Klass test2 = instantiate(ktype, ctor, [2]);
Klass test3 = instantiate(reflect(kinstance).type.reflectedType, ctor, [3]);
Klass test4 = instantiate(Klass, #fromString, ["4"]);

print(test1.i1);
print(test2.i1);
print(test3.i1);
print(test4.i1);
}

dynamic instantiate(Type type, Symbol constructorName, List positional, [Map named]) {
return reflectClass(type).newInstance(constructorName, positional, named).reflectee;
}

class Klass {
int i1;
Klass( int i1 ) {
this.i1 = (i1 is int) ? i1 : 0;
}

Klass.fromString(String i) {
i1 = int.parse(i, onError : (s) => i1 = 0);
}
}

输出:

1
2
3
4

关于dart - 需要 Dart 镜像 instantiate() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21226474/

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