정적 멤버와 인스턴스 멤버
Coddy의 R 개발자를 위한 C# 코스 레슨. 48개 중 35번째.
R 클래스에는 정적 멤버가 없습니다. 생성 카운터와 같은 공유 상태는 보통 환경에 저장됩니다. 함수 안에서 전역 이름에 값을 할당하면 <<-를 사용하거나 환경을 수정하지 않는 한 지역 변수만 생성되기 때문입니다. C# 정적 필드는 형식 자체에 속하며 Unit.Label로 접근합니다. 공유 카운터는 형식에, 티켓별 값은 인스턴스에 두세요.
정적 멤버는 인스턴스가 아니라 형식에 속합니다. 공유가 의도된 경우에만 공유 카운터로 적합합니다. 인스턴스 필드에는 각 객체의 값이 계속 저장됩니다. 명시적으로 초기화하면 이 연습을 반복할 수 있습니다. 관련 없는 설계에서는 숨겨진 공유 상태를 피하세요.
R 참고 코드
registry <- new.env()
new_ticket <- function(value) {
registry$created <- registry$created + 1
structure(list(value = value), class = "ticket")
}
registry$created <- 0
a <- new_ticket(4)
b <- new_ticket(7)
cat(registry$created, "\n", sep = "")C# 보조 선언
class Unit { public static string Label = "shared"; public string Name; public Unit(string name) { Name = name; } }Main 내부의 C# 문
var a = new Unit("one");
var b = new Unit("two");
Console.WriteLine(Unit.Label + ":" + a.Name + ":" + b.Name);이 내용은 핵심을 다루는 학습용 발췌문입니다. 챌린지 파일에는 실행 가능한 완전한 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문을 보여 줍니다.
참고 출력:
2C# 출력:
shared:one:two챌린지
쉬움Ticket을 완성하세요. 각 생성자는 시드 값을 Value에 저장하고 공유되는 Created 개수를 증가시킵니다. Reset은 Created를 0으로 설정합니다. Solve는 초기화한 다음 입력값마다 티켓을 하나씩 만들고 개수:값 형식으로 반환합니다. 인스턴스의 값은 서로 독립적으로 유지되어야 합니다.
잠금 해제된 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);
Ticket.Reset(); var t1 = new Ticket(4); var t2 = new Ticket(9); if (Ticket.Created != 2 || t1.Value != 4 || t2.Value != 9) throw new Exception("Ticket API"); Ticket.Reset(); if (Ticket.Created != 0) throw new Exception("Reset API");
var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
R 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 번째 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러