是否有一种方法来动态调用方法或在Dart中的类中设置实例变量? [英] Is there a way to dynamically call a method or set an instance variable in a class in Dart?

查看:773
本文介绍了是否有一种方法来动态调用方法或在Dart中的类中设置实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Dart类构造函数做这样的事情:

I would want to be able to do something like this with a Dart class constructor:

class Model {

  // ... setting instance variables

  Model(Map fields) {
    fields.forEach((k,v) => this[k] = v);
  }

}

显然,这不工作,因为没有 [] = 方法。

Obviously, this doesn't work, because this doesn't have a []= method.

有没有办法使它工作,或者它根本不是飞镖的方式做事情?

Is there a way to make it work or is it simply not "the dart way" of doing things? If it's not, could you show me what would be the right way to tackle this?

推荐答案

目前没有。如果没有,您能告诉我什么是正确的方法来解决这个问题。你将不得不等待反射到达Dart在这样的东西(希望)成为可能。直到那时,你最好的打赌可能是在一个构造函数。或者,您可以尝试使用类似于 JsonObject 的方法,它允许您从地图直接初始化它对此工作原理的说明,请查看 blog post)。

Currently no. You will have to wait for reflection to arrive in Dart before something like this (hopefully) becomes possible. Until then your best bet is probably to do it in a constructor. Alternatively you could try to use something like JsonObject which allows you to directly initialize it from a Map (for an explanation on how this works, check this blog post).

这篇关于是否有一种方法来动态调用方法或在Dart中的类中设置实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆