使用变量作为键访问对象值

编程入门 行业动态 更新时间:2024-10-27 00:30:09
本文介绍了使用变量作为键访问对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用以前在dart中定义的变量来访问类值,但我不断收到错误未为该类定义运算符[]

I'm trying to access a class value by using a variable previously defined in dart, but I keep getting the error the operator [] isn't defined for the class

在Java语言中,我将使用如下变量访问对象值:

In Javascript I would access an object value using a variable like this:

let movie = { movieTitle : 'Toy Story', actor: 'Tom Hanks' } let actorName = 'actor'; console.log(movie[actorName]); // <- what I'm trying to replicate in dart // expected output: Tom Hanks

这是我尝试过并抛出的错误

Here is what I've tried and is throwing that error

class Movie { String name; String actor; String producer; } void main() { var movieTitle = new Movie(); movieTitle.name = 'Toy Story'; movieTitle.actor = 'Tom Hanks'; print(movieTitle.actor); <- prints out Tom Hanks as expected var actorName = 'actor'; print(movieTitle[actorName]); <- throws error }

我希望能够在飞来获取价值。

I expect to be able to use a variable on the fly to access the value.

对我来说,一个微不足道的用例是,如果我有一个电影类列表,其中一些演员和制片人为空,我想过滤两个非空演员或具有以下功能的制作人:

A trivial use case for me would be if I had a a list of Movie classes, where some actors and producers are null, I would like to filter on either non null actors or producer with a function like so:

List values = movieList.where((i) => i.actor != "null").toList(); // returns all Movies in movieList where the actor value isn't the string "null" var actorIsNull = 'actor'; List values = movieList.where((i) => i[actorisNull] != "null").toList(); // throws error

推荐答案

包含其名称的字符串。 (带镜子-不在此答案范围内。)

You cannot access class members by a string containing their name. (Except with mirrors - outside the scope of this answer.)

您可以完全删除该类,而只需使用 Map< String,String> 。

You could remove the class altogether and just use a Map<String, String>.

Map<String, String> movie = { 'movieTitle': 'Toy Story', 'actor': 'Tom Hanks', }

您可以在类中添加一些 bool 方法。

You could add some bool methods on the class.

bool hasNoActor() => actor == null; ... List values = movieList.where((m) => !m.hasNoActor()).toList();

或者,您可以将lambda传递给映射器。

Or, you could pass a lambda to your mapper.

Movie movieTitle = Movie() ..name = 'Toy Story' ..actor = 'Tom Hanks'; Function hasActor = (Movie m) => m.actor != null; List values = movieList.where(hasActor).toList();

更多推荐

使用变量作为键访问对象值

本文发布于:2023-11-23 17:37:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622317.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!