问题描述
我想使用Dart 2克隆一个复杂的对象(复制值),而不是引用。
I would like to clone a complex object (copy values), not referencing, using Dart 2.
示例:
class Person {
String name;
String surname;
City city;
}
class City {
String name;
String state;
}
main List<String> args {
City c1 = new City()..name = 'Blum'..state = 'SC';
Person p1 = new Person()..name = 'John'..surname = 'Xuebl'..city = c1;
Person p2 = // HERE, to clone/copy values... Something similar to p1.clone();
}
这样做的最佳方式是什么?
What would be the way (best practice) to do this?
更新说明::此这里的重点是了解进行了许多改进的Dart 2是否具有复制复杂对象的功能。
Update note: This How can I clone an Object (deep copy) in Dart? was posted some time ago. The focus here is to understand if Dart 2 that is bringing many improvements, has a facility for copying complex objects.
推荐答案
您在这里向我们展示的课程,没有什么比
With the classes you have shown us here, there is nothing shorter than
Person p2 = Person()
..name = p1.name
..surname = p1.surname
..city = (City()..name = p1.city.name..state = p1.city.state);
如果您将 clone
方法添加到人
和城市
,那么您显然可以使用它。
该语言没有内置功能可让您复制对象的状态。
If you add a clone
method to Person
and City
, then you can obviously use that.There is nothing built in to the language to allow you to copy the state of an object.
我建议更改类,至少要添加一个构造函数:
I would recommend changing the classes, at least by adding a constructor:
class Person {
String name;
String surname;
City city;
Person(this.name, this.surname, this.city);
}
class City {
String name;
String state;
City(this.name, this.state);
}
然后您可以通过以下方式克隆:
Then you can clone by just writing:
Person P2 = Person(p1.name, p1.surname, City(p1.city.name, p1.city.state));
(还有)
我说有没有语言功能可以复制对象,但是实际上,如果您可以访问 dart:isolate
库,则可以:通过隔离通信端口发送对象。我不建议您使用该功能,但这是出于完整性考虑:
I say that there is no language feature to copy objects, but there actually is, if you have access to the dart:isolate
library: Sending the object over a isolate communication port. I cannot recommend using that feature, but it's here for completeness:
import "dart:isolate";
Future<T> clone<T>(T object) {
var c = Completer<T>();
var port = RawReceivePort();
port.handler = (Object o) {
port.close();
c.complete(o);
}
return c.future;
}
同样,我不建议使用这种方法。
它适用于像这样的简单对象,但不适用于所有对象(并非所有对象都可以通过通信端口发送,例如,一等函数或任何包含一等函数的对象)。
Again, I cannot recommend using this approach.It would work for simple objects like this, but it doesn't work for all objects (not all objects can be sent over a communication port, e.g., first-class functions or any object containing a first class function).
编写类以支持所需的操作,包括复制。
Write your classes to support the operations you need on them, that includes copying.
这篇关于如何在Dart 2中克隆(复制值)复杂对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!