Menu
CoddyTech

동일성과 복사본

Coddy의 C# 개발자를 위한 Dart 코스 레슨. 48개 중 30번째.

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}');}
challenge icon

챌린지

쉬움

Notebook(List<String> items)를 구현할 때 입력값을 복사하세요. add(String item)은 항목을 추가하고, getter인 size는 개수를 읽으며, snapshot()은 새 목록을 반환합니다. 입력값이나 스냅샷을 변경해도 노트북에는 영향을 주지 않아야 합니다. 입력값은 0개 이상의 단어입니다. 래퍼는 스냅샷을 가져와 비우고, 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));
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C# 개발자를 위한 Dart의 모든 레슨

직접 연습해 보세요: 온라인 Dart 컴파일러