Menu
CoddyTech

메서드, 기본값 및 params

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

Python의 *args는 C#의 params 배열에 해당합니다. C#의 선택적 인수는 선언된 형식으로 제한되므로 Python 방식의 제약 없는 인수 조합을 의미하지는 않습니다. 정적 C# 헬퍼 메서드는 형식에 속하지만, Python 모듈 함수에는 이를 감싸는 클래스가 필요하지 않습니다.

정적 메서드는 인스턴스가 아니라 형식에 속합니다. 선택적 매개변수는 인수를 생략했을 때 기본값을 제공합니다. params 배열은 뒤따르는 위치 인수를 모으거나 기존 배열을 받습니다. 결과 형식을 명시적으로 유지하세요. 값을 반환하는 것과 출력하는 것은 서로 다릅니다.

Python 참조 코드

def total(factor=2, *values):
    return sum(values) * factor
print(total(3, 2, 4))

C# 보조 선언

static string JoinTags(string prefix = "tags", params string[] tags) { return prefix + ":" + string.Join(",", tags); }

Main 내부의 C# 문장

Console.WriteLine(JoinTags("names", "A", "B"));

이 내용은 핵심만 다룬 교육용 발췌문입니다. 과제 파일에는 실행 가능한 전체 래퍼가 포함되어 있으며, 위 코드 조각에는 관련 선언과 문장이 나와 있습니다.

참조 출력:

18

C# 출력:

names:A,B
challenge icon

챌린지

쉬움

정수 시퀀스와 인수를 읽으세요. 기본값이 2인 선택적 인수와 params 정수 배열을 받는 Total을 구현하세요. Solve는 Total을 호출하고 합계에 인수를 곱한 값을 반환합니다. 잠긴 main은 Total을 기본 인수로, 그리고 별도의 인수들과 함께 호출하기도 합니다.

잠금 해제된 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);
var a1 = I(input[1]); string before1=Snapshot(a1);
if (Exercise.Total() != 0 || Exercise.Total(2, 3, 4) != 14) throw new Exception("Total API");
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(result);
}
}
quiz icon실력 점검

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

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

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