gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 06:29:46 25 4
gpt4 key购买 nike

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/

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