对象标识与副本
Coddy 面向 C# 开发者的 Dart 课程的第 30 课,共 48 课。
C# 中的 ReferenceEquals 和 Dart 中的 identical 会明确检查对象标识。C# 运算符重载和 Dart 的 == 重写可以定义值相等性。复制外层列表会保留嵌套列表的引用。
identical 会检查对象标识。类可以重写相等运算符。浅拷贝只会复制外层容器,因此在承诺提供快照时,要考虑嵌套引用。
完整的 C# 程序:
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main(){var a=new List<List<int>>{new List<int>{1}};var b=new List<List<int>>(a);b[0].Add(2);Console.WriteLine(Object.ReferenceEquals(a,b)+":"+a[0].Count);}
}
完整的 Dart 程序:
void main(){final a=<List<int>>[[1]];final b=List<List<int>>.of(a);b[0].add(2);print('${identical(a,b)}:${a[0].length}');}挑战
简单通过复制输入来实现 Notebook(List<String> items)。add(String item) 会追加内容,getter size 会读取数量,而 snapshot() 会返回一个新的列表。修改输入或快照都不会影响笔记本。输入包含零个或多个单词。包装函数会获取一个快照、清空它、添加 done,然后返回大小。
不要在可编辑文件中打印内容。提供的 exercise.dart 会解析输入并返回输出;锁定的驱动程序会独立测试公开 API,并在结果后打印一个换行符。
你的代码应写在 Notebook.dart、exercise.dart 中。main.dart 包含提供的输入输出代码,不能编辑。
亲手试试
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Notebook.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final a=['x'];final n=Notebook(a);a.clear();check(n.size==1);final s=n.snapshot();check(s.join(',')=='x');s.clear();n.add('y');check(n.size==2 && n.snapshot().join(',')=='x,y');
stdout.writeln(solve(input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Dart中的所有课
自己练习: Dart 在线编译器