Menu
CoddyTech

객체 합성

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

C# 및 GDScript의 클래스 참조 필드는 같은 협력 객체를 공유할 수 있습니다. 이 참조를 저장해도 객체가 복제되지 않으며, 나중에 변경한 내용도 별칭을 통해 확인할 수 있습니다. 생성자 주입을 사용하면 대체 협력 객체의 동작을 확인하고 테스트할 수 있습니다. 수명 관리는 서로 다릅니다. .NET의 가비지 컬렉션은 도달할 수 없는 관리 대상 순환 참조를 회수할 수 있지만, RefCounted의 강한 순환 참조는 자동으로 회수되지 않습니다. 순환하는 강한 소유 관계 대신 명확한 소유권 방향을 사용하거나 WeakRef를 사용하세요. 여기서는 봉투가 메모를 관찰하고, 연습 문제에서는 가격 계산 작업을 위임합니다.

C# 비교 예제를 완성하세요. 나열된 모든 C# 파일을 함께 컴파일하세요. Program.Main이 진입점입니다.

C# 파일 DemoNote.cs:

public class DemoNote { public string Text="a"; }

C# 파일 DemoEnvelope.cs:

public class DemoEnvelope { public DemoNote Note; public DemoEnvelope(DemoNote note){Note=note;} }

C# 파일 Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
public static class Program {

public static void Main() {
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var n=new DemoNote();var e=new DemoEnvelope(n);n.Text="b";Console.WriteLine(e.Note.Text);
}
}

C# 출력:

b

GDScript 예제 파일 demo_note.gd:

class_name DemoNote
extends RefCounted
var text: String = "a"

GDScript 예제 파일 demo_envelope.gd:

class_name DemoEnvelope
extends RefCounted
var note: DemoNote
func _init(value: DemoNote) -> void:
	note = value

GDScript 예제 파일 main.gd:

extends Node

func _ready() -> void:
	var note: DemoNote = DemoNote.new()
	var envelope: DemoEnvelope = DemoEnvelope.new(note)
	note.text = "b"
	print(envelope.note.text)

GDScript 출력:

b
challenge icon

챌린지

쉬움

RateRule(cents:int)를 구현하고 cost(units:int)를 제공하세요. BillBox(rule:RateRule)는 전달된 규칙을 저장하고, total(units:int)은 해당 규칙에 위임합니다. 이후 rule.cents를 변경하면 청구 금액에 반영되어야 합니다. Solve는 [rate,units]를 사용합니다.

입력은 stdin에 전달되는 하나의 JSON 배열입니다. 수정할 수 없는 main은 이를 파싱하고, 공개 API를 호출한 다음 반환된 텍스트 앞에 result=를 붙여 출력하고 줄바꿈을 합니다. 어떤 헬퍼도 출력해서는 안 됩니다. 입력 사례를 처리하기 전에 독립적인 고정 프로브로 필수 API 동작을 확인하지만, 구현 방식은 제한하지 않습니다.

코드는 rate_rule.gd, bill_box.gd, exercise.gd에 작성하세요. main.gd에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다. 각 class_name 형식은 이름에 해당하는 파일에 두세요.

직접 해보기

extends Node

func contract_ok(data: Array) -> bool:
	var rule: RateRule = RateRule.new(2)
	var bill: BillBox = BillBox.new(rule)
	rule.cents = 7
	if rule.cost(3) != 21 or bill.total(3) != 21: return false
	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))
quiz icon실력 점검

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

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

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