Menu
CoddyTech

생성자와 인스턴스

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

C에서는 호출자가 호출하는 것을 잊을 수 있는 init 함수로 구조체를 설정하며, 초기화되지 않은 자동 구조체에는 쓰레기 값이 들어 있습니다. 정의를 볼 수 있는 모든 코드에서 모든 멤버를 볼 수 있습니다. C#에서는 new가 객체를 생성할 때 생성자가 항상 실행되고, 할당되지 않은 필드는 0 또는 null로 시작하며, private 멤버는 컴파일러에 의해 강제됩니다. C 구조체 값과 달리 클래스 인스턴스는 대입할 때 참조로 공유되며, 가비지 컬렉터가 이를 해제합니다.

생성자는 유효한 인스턴스를 만듭니다. 인스턴스 메서드는 this를 통해 해당 객체에서 동작하고, 필드는 호출이 이어지는 동안 객체의 상태를 유지합니다. 각 업데이트를 제한하는 것은 최종 합계만 제한하는 것과 다릅니다. 재사용 가능한 클래스는 연습 코드 및 실행 코드와 별도의 소스 파일에 둡니다.

C 참조 코드

#include <stdio.h>

struct Counter { int count; };

static int clamp_zero(int n) { return n < 0 ? 0 : n; }

static void counter_init(struct Counter *c, int n) { c->count = clamp_zero(n); }
static void counter_add(struct Counter *c, int n) { c->count = clamp_zero(c->count + n); }
static int counter_value(const struct Counter *c) { return c->count; }

int main(void) {
    struct Counter counter;          /* counter_init이 실행되기 전까지는 쓰레기 값 */
    counter_init(&counter, 1);
    counter_add(&counter, 3);
    printf("%d\n", counter_value(&counter));
    return 0;
}

C# 보조 선언

class NamedItem { public string Name { get; private set; } public NamedItem(string name) { Name = name; } }

Main 내부의 C# 문

var item = new NamedItem("pen");
Console.WriteLine(item.Name);

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

참조 출력:

4

C# 출력:

pen
challenge icon

챌린지

쉬움

Counter.cs에서 Counter를 완성하세요. max(0, initial)으로 초기화하세요. 변경 사항을 한 번에 하나씩 더하고, 더할 때마다 상태가 0보다 작아지지 않도록 제한하세요. Value를 노출하세요. 별도의 인스턴스끼리는 상태를 공유하면 안 됩니다.

잠금 해제된 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 c1 = new Counter(1); var c2 = new Counter(7); c1.Add(-5); c1.Add(2); if (c1.Value != 2 || c2.Value != 7 || new Counter(-1).Value != 0) throw new Exception("Counter 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실력 점검

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

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

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