Menu
CoddyTech

가상 메서드와 override

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

모든 Lua 메서드 호출은 동적입니다. plan:total(2)는 객체에서 total을 찾은 다음 객체의 __index 체인을 따라 찾으므로, 해당 메서드를 정의한 첫 번째 테이블이 사용됩니다. 재정의에는 키워드가 필요하지 않으며, 기본 버전을 호출하려면 Plan.total(self, n)처럼 이름을 명시해야 합니다. C# 메서드는 기본적으로 가상 메서드가 아닙니다. 기본 클래스에서 virtual로 선언하고 파생 클래스에서 override를 작성해야 합니다. new로 선언한 멤버는 기본 클래스의 멤버를 숨길 뿐이므로, 테스트는 기본 클래스 형식을 통해 호출합니다.

가상 멤버는 파생 클래스에서 재정의할 수 있습니다. override는 기본 클래스 참조를 통한 다형적 디스패치를 유지하지만, new로 멤버를 숨기는 것은 다릅니다. 파생 클래스 생성자는 공유 상태를 초기화하기 위해 base를 호출할 수 있습니다. 하위 형식이 기본 계약을 준수하는 경우에만 상속을 사용하세요.

Lua 참고 코드

local Plan = {}
Plan.__index = Plan
function Plan.new(unit)
  return setmetatable({unit = unit}, Plan)
end
function Plan:total(n)
  return self.unit * n
end
local DiscountPlan = setmetatable({}, {__index = Plan})
DiscountPlan.__index = DiscountPlan
function DiscountPlan.new(unit)
  return setmetatable(Plan.new(unit), DiscountPlan)
end
function DiscountPlan:total(n)
  return Plan.total(self, n) * 9 // 10
end
local plan = DiscountPlan.new(10)
print(plan:total(2))

C# 지원 선언

class Message { public virtual string Speak() { return "hello"; } }
class LoudMessage : Message { public override string Speak() { return base.Speak().ToUpperInvariant(); } }

Main 내부의 C# 문장

Message message = new LoudMessage();
Console.WriteLine(message.Speak());

이 내용은 특정 주제를 다루는 학습용 발췌문입니다. 과제 파일에는 실행 가능한 전체 래퍼 코드가 포함되어 있으며, 위 코드 조각은 관련 선언과 문장만 보여 줍니다.

Lua 출력:

18

C# 출력:

HELLO
challenge icon

챌린지

쉬움

Plan.Total과 DiscountPlan.Total을 완성하세요. 기본 요금은 unit * count입니다. DiscountPlan은 기본 정수 합계의 90퍼센트를 내림한 값을 반환합니다. 음이 아닌 입력에서는 곱이 작게 유지됩니다. 드라이버는 가상 디스패치를 요구하기 위해 Plan 참조를 통해 호출합니다.

잠금 해제된 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 = I(input[1]); string before1=Snapshot(a1);
var a2 = input[2] == "true"; string before2=Snapshot(a2);
Plan p1 = new DiscountPlan(10); Plan p2 = new Plan(10); if (p1.Total(3) != 27 || p2.Total(3) != 30) throw new Exception("Virtual API");
var result = Exercise.Solve(a0,a1,a2);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
if (Snapshot(a2) != before2) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon실력 점검

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

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

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