Menu
CoddyTech

리스트와 안전한 업데이트

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

JavaScript의 push는 배열을 확장하고, C#의 List<T>.Add는 형식이 지정된 리스트를 확장하지만 C# 배열은 크기가 고정되어 있습니다. 두 언어 모두 대입하면 동일한 변경 가능한 객체를 참조하게 됩니다. List<int> 복사 생성자는 독립적인 바깥쪽 시퀀스를 만듭니다.

List<T>는 배열과 달리 크기를 조정할 수 있습니다. Count는 요소의 개수를 반환하고, Add는 값을 추가합니다. 다른 리스트에서 새 List<int>를 생성하면 정수 요소가 복사되지만, 대입은 참조만 복사합니다. 잠긴 드라이버는 원본이 변경되지 않는지 확인합니다.

JavaScript 참고

const values = [2];
values.push(5);
console.log(values.length);

Main 내부의 C# 문

var values = new List<int> { 2 };
values.Add(5);
Console.WriteLine(values.Count);

이 예제는 핵심 내용을 가르치기 위한 발췌문입니다. 챌린지 파일에는 실행 가능한 전체 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문을 보여 줍니다.

참조 출력:

2

C# 출력:

2
challenge icon

챌린지

쉬움

정수 리스트가 있는 줄과 추가 정수가 있는 줄을 읽으세요. 추가 정수를 뒤에 붙인 새 리스트를 반환하세요. 전달된 리스트는 수정하지 마세요. 드라이버는 values: 뒤에 쉼표로 구분된 값을 출력합니다.

잠금 해제된 C# 파일을 수정하세요. 표시된 잠금 상태의 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하며, 입력이 변경되지 않았는지 확인하고 결과를 끝에 줄바꿈 하나를 붙여 출력합니다. 선언된 API를 유지하세요. 두 번째 Main을 추가하거나 진단 출력을 표시하지 마세요.

직접 해보기

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = new List<int>(Ints(input[0])); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);

var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine("values:" + string.Join(",", result));
}
}
quiz icon실력 점검

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

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

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