arrays - 如何在 Dart 中将对象转换为数组(映射)?

标签 arrays object reflection dart type-conversion

Dart中如何将Object类型转换为Map类型(数组),让变量变成键/值对?

最佳答案

/**
   * Uses refection (mirrors) to produce a Map (array) from an object's
   * variables. Making the variable name the key, and it's value the
   * value.
   */
  Map objectToMap(Object object)
  {
    // Mirror the particular instance (rather than the class itself)
    InstanceMirror instanceMirror = reflect(object);
    Map dataMapped = new Map();

    // Mirror the instance's class (type) to get the declarations
    for (var declaration in instanceMirror.type.declarations.values)
    {
      // If declaration is a type of variable, map variable name and value
      if (declaration is VariableMirror)
      {
        String variableName = MirrorSystem.getName(declaration.simpleName);
        String variableValue = instanceMirror.getField(declaration.simpleName).reflectee;

        dataMapped[variableName] = variableValue;
      }
    }

    return dataMapped;
  }

关于arrays - 如何在 Dart 中将对象转换为数组(映射)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27405953/

相关文章:

java - 我正在尝试使用一种方法来查找数组中哪些数字大于 20 并返回一个百分比

c# - 目录列表递归

c# - 有没有办法交替使用 ParameterInfo 和 PropertyInfo?

php - 合并不同长度的数组php

javascript - 如何在 if 语句中使用对象 - Javascript

javascript - 在 JavaScript 中将几个数组组合成一个对象数组

javascript - 仅对一个变量设置状态

vb.net - 在 VB.NET 中对对象列表进行排序

处理数组的对象的 Java 字符串表示形式

c# - 获取泛型类型参数的数量