Menu
CoddyTech

대리자와 클로저

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

Python의 호출 가능 객체와 람다는 직접 전달할 수 있습니다. C#의 Func<int,int>는 int 입력 하나와 int 결과 하나를 나타내는 대리자 형식입니다. 둘 다 둘러싼 변수를 캡처할 수 있지만, C#은 컴파일 시 매개변수와 반환 형식을 검사합니다.

대리자는 매개변수와 반환 형식이 검사되는 호출 가능 값을 나타냅니다. Func<int,int>는 int를 받아 int를 반환합니다. 람다는 둘러싼 범위의 변수를 캡처할 수 있습니다. 블록 본문이 있는 람다는 값을 명시적으로 반환해야 합니다. 식 본문이 있는 람다는 식의 값을 반환합니다.

Python 참조

offset = 4
add = lambda value: value + offset
print(add(3))

Main 내부의 C# 문

int offset = 4;
Func<int,int> add = value => value + offset;
Console.WriteLine(add(3));

이 내용은 핵심에 초점을 둔 학습용 발췌문입니다. 과제 파일에는 실행 가능한 완전한 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문을 보여 줍니다.

참조 출력:

7

C# 출력:

7
challenge icon

챌린지

쉬움

각 값에 offset을 더한 새 배열을 반환하세요. offset을 캡처하는 Func<int,int> 콜백을 정의하고, 입력을 변경하지 않고 적용하세요.

잠금 해제된 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 = 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실력 점검

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

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

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