생성자와 인스턴스
Coddy의 Ruby 개발자를 위한 C# 코스 레슨. 48개 중 33번째.
Ruby의 initialize와 self는 C#의 생성자와 this에 해당하며, Counter.new(1)은 new Counter(1)이 됩니다. Ruby의 인스턴스 변수는 attr_reader를 추가하기 전까지 숨겨져 있습니다. C#의 멤버는 액세스 한정자에 따라 표시되며, private set은 클래스 내부에서만 값을 쓸 수 있게 합니다. 두 객체 모델 모두 공유되는 @@ 클래스 변수나 정적 카운터가 아니라, 서로 구분되는 인스턴스 상태가 필요합니다.
생성자는 유효한 인스턴스를 만듭니다. 인스턴스 메서드는 this를 통해 해당 객체를 다루고, 필드는 호출 사이에도 그 객체의 상태를 유지합니다. 각 업데이트마다 값을 제한하는 것과 최종 합계에만 제한을 적용하는 것은 다릅니다. 재사용할 클래스는 연습 코드 및 실행 코드와 별도의 소스 파일에 넣으세요.
Ruby 참고 코드
class Counter
attr_reader :count
def initialize(initial)
@count = [0, initial].max
end
def add(n)
@count = [0, @count + n].max
end
end
counter = Counter.new(1)
counter.add(3)
puts counter.countC# 보조 선언
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);이 내용은 핵심에 초점을 맞춘 학습용 발췌문입니다. 과제 파일에는 실행에 필요한 전체 래퍼 코드가 포함되어 있으며, 위 코드 조각은 관련 선언과 문장을 보여 줍니다.
Ruby 출력:
4C# 출력:
pen챌린지
쉬움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);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Ruby 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 번째 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러