Menu
CoddyTech

out 매개변수와 계약

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

Python은 여러 결과를 반환할 때 흔히 튜플을 반환합니다. C#의 out은 호출자의 바인딩을 통해 추가 결과를 전달하며, 메서드는 정상적인 모든 경로에서 해당 값을 할당해야 합니다. 성공 여부가 false라면 할당되지 않은 값이 모호하게 남지 않도록 해야 합니다.

out 매개 변수는 호출자의 바인딩을 통해 추가 값을 반환하며 모든 경로에서 할당되어야 합니다. bool과 out을 함께 사용하는 규칙은 결과가 없는 경우와 유효한 0을 구분합니다. 모든 값이 음수인 시퀀스에서 최댓값을 0으로 시작하는 것은 잘못입니다. 빈 시퀀스를 처리한 다음 첫 번째 값으로 초기화하세요.

Python 참고 코드

def try_double(value):
    return True, value * 2
ok, n = try_double(4)
print(n if ok else "invalid")

C# 보조 선언

static bool TryDouble(int value, out int result) { result = value * 2; return true; }

Main 내부의 C# 문

int n;
Console.WriteLine(TryDouble(4, out n) ? n.ToString() : "invalid");

다음은 특정 개념을 설명하기 위한 발췌문입니다. 챌린지 파일에는 완전하게 실행 가능한 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문을 보여 줍니다.

참조 출력:

8

C# 출력:

8
challenge icon

챌린지

쉬움

TryMaximum(int[] values, out int maximum)을 구현하세요. 빈 배열이면 false를 반환하고 maximum을 0으로 설정하세요. 그렇지 않으면 모든 값이 음수인 경우에도 true를 반환하고 가장 큰 값을 설정하세요. Solve는 결과의 형식을 지정합니다.

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

잠긴 실행기는 Solve 래퍼뿐만 아니라 내보낸 도우미 또는 클래스 API도 별도로 확인합니다.

직접 해보기

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);
int maximum; if (Exercise.TryMaximum(new int[0], out maximum) || maximum != 0 || !Exercise.TryMaximum(new[]{-8,-3},out maximum) || maximum != -3) throw new Exception("TryMaximum API");
var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon실력 점검

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

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

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