열거형과 switch
Coddy의 Go 개발자를 위한 C# 코스 레슨. 48개 중 10번째.
iota를 사용하는 Go의 형식 지정 상수는 열거형과 비슷한 관용구이지만, 형식을 이름이 지정된 값으로 제한하지는 않습니다. C#에서 열거형을 형변환해도 이름이 지정되지 않은 정수를 사용할 수 있습니다. Go의 switch 케이스는 기본적으로 다음 케이스로 넘어가지 않지만, C#의 전통적인 switch에서는 분기를 명시적으로 종료해야 합니다.
열거형은 유한한 어휘를 지정하지만, 정수를 형변환하면 이름이 지정된 멤버가 없는 값이 나올 수 있습니다. 따라서 switch의 default 분기를 사용해 잘못된 숫자 상태를 처리해야 합니다. 이 컴파일러와 호환되는 전통적인 switch 문을 사용하고, 최신 switch 식은 사용하지 마세요.
Go 참조 코드
package main
import ("fmt")
type State int
const (Draft State=iota; Paid; Sent)
func main() {
state:=Paid; switch state { case Draft:fmt.Println("Draft"); case Paid:fmt.Println("Paid"); default:fmt.Println("unknown") }
}C# 보조 선언
enum State { Draft, Paid, Sent }Main 내부의 C# 문
State state = State.Paid;
Console.WriteLine(state.ToString());이 내용은 핵심을 설명하기 위한 발췌문입니다. 과제 파일에는 실행 가능한 전체 래퍼 코드가 포함되어 있으며, 위 코드 조각은 관련 선언과 문을 보여 줍니다.
참조 출력:
PaidC# 출력:
Paid챌린지
쉬움입력은 상태 코드입니다. 0은 초안, 1은 결제 완료, 2는 발송 완료입니다. 각각 edit, pack 또는 track을 반환하고, 다른 정수 코드는 invalid를 반환합니다. 별도의 파일에 제공된 State 열거형을 사용하세요.
잠금이 해제된 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 = (State)I(input[0]); string before0=Snapshot(a0);
var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Go 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 번째 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러