Menu
CoddyTech

out 매개변수와 계약

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

C++의 const가 아닌 참조 매개변수는 추가 결과를 반환할 수 있지만, C#의 out 확정 할당 규칙을 강제하지는 않습니다. C#의 out은 정상적으로 반환되기 전에 반드시 값이 할당되어야 하며, 들어오는 값이 메서드의 입력값이 아님을 나타냅니다.

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

C++ 참조

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
bool tryDouble(int value,int& result) { result=value*2; return true; }
int main() {
int n=0;
cout << (tryDouble(4,n)?to_string(n):"invalid") << "\n";
}

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실력 점검

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

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

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