리스트와 안전한 업데이트
Coddy의 PHP 개발자를 위한 C# 코스 레슨. 48개 중 16번째.
PHP 배열은 $values[] = 5 또는 array_push를 사용해 확장됩니다. C# List<T>.Add는 형식이 지정된 목록을 확장하지만, C# 배열의 크기는 고정되어 있습니다. PHP 배열을 대입하면 배열이 복사되지만(쓰기 시 복사), C# List를 대입하면 같은 객체를 공유합니다. List<int> 복사 생성자는 독립적인 바깥쪽 시퀀스를 만듭니다.
List<T>는 배열과 달리 크기를 조정할 수 있습니다. Count는 요소의 개수를 반환하고, Add는 값을 추가합니다. 다른 List<int>에서 새 List<int>를 만들면 정수 요소가 복사되지만, 대입하면 참조만 복사됩니다. 잠금 처리된 드라이버는 원본이 변경되지 않았는지 확인합니다.
PHP 참조
<?php
$values = [2];
$values[] = 5;
echo count($values), "\n";Main 내부의 C# 문장
var values = new List<int> { 2 };
values.Add(5);
Console.WriteLine(values.Count);이 내용은 특정 개념을 가르치기 위한 발췌문입니다. 과제 파일에는 실행 가능한 전체 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문장만 보여 줍니다.
참조 출력:
2C# 출력:
2챌린지
쉬움정수 목록이 있는 줄과 추가 정수 줄을 읽으세요. 추가 정수를 끝에 덧붙인 새 목록을 반환하세요. 전달된 목록은 수정하지 마세요. 드라이버는 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));
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
PHP 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 번째 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러