속성으로 불변식 보호하기
Coddy의 C 개발자를 위한 C# 코스 레슨. 48개 중 34번째.
C에는 구조체 멤버에 대한 접근 제어가 없습니다. 정의를 볼 수 있는 코드는 무엇이든 account.amount에 직접 값을 할당할 수 있으므로, C 라이브러리는 불투명 포인터와 account_balance 같은 getter 함수 뒤에 상태를 숨깁니다. C#에서는 필드를 private으로 유지하고, 호출자가 필드처럼 읽을 수 있는 속성을 공개하며, 접근자가 허용되는 작업을 결정합니다. getter만 있는 속성은 C의 getter 함수처럼 읽기 접근을 제공하고, 모든 업데이트가 유효성을 검사하는 메서드를 거치도록 합니다.
속성은 제어된 접근을 제공하고, 비공개 필드는 불변 조건을 유지합니다. getter는 호출자가 임의의 값을 할당할 수 없게 하면서 상태를 보여줄 수 있습니다. 비공개 setter 또는 getter만 있는 속성은 계약상의 선택입니다. 업데이트에 유효성 검사가 필요하다면 변경 가능한 필드를 공개하지 마세요.
C 참고 코드
#include <stdio.h>
struct Account { int amount; };
static void account_init(struct Account *a, int n) { a->amount = n > 0 ? n : 0; }
static void account_deposit(struct Account *a, int n) { if (n > 0) a->amount += n; }
static int account_balance(const struct Account *a) { return a->amount; }
int main(void) {
struct Account account;
account_init(&account, 5);
account_deposit(&account, -3);
printf("%d\n", account_balance(&account));
account.amount = -100; /* 컴파일됨: 멤버를 숨기는 것이 없음 */
printf("%d\n", account_balance(&account));
return 0;
}
C# 보조 선언
class Reading { private int raw; public Reading(int raw) { this.raw = raw; } public int Doubled { get { return raw * 2; } } }Main 내부의 C# 문
var reading = new Reading(3);
Console.WriteLine(reading.Doubled);이 예제는 핵심 개념을 설명하기 위해 발췌한 것입니다. 과제 파일에는 완전한 실행 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문을 보여줍니다.
참고 출력:
5
-100C# 출력:
6챌린지
쉬움Account를 완성하세요. 시작 잔액은 0으로 제한하고, 양수 입금액은 잔액을 늘리며, 0 이하의 입금액은 무시합니다. 잔액은 읽을 수 있지만 공개적으로 설정할 수는 없습니다.
잠금 해제된 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 = I(input[0]); string before0=Snapshot(a0);
var a1 = Ints(input[1]); string before1=Snapshot(a1);
var accountOne = new Account(-2); var accountTwo = new Account(5); accountOne.Deposit(3); accountOne.Deposit(-9); if (accountOne.Balance != 3 || accountTwo.Balance != 5) throw new Exception("Account 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);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러