Menu
CoddyTech

인터페이스 기반 디스패치

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

C에서 어떤 알림기와도 함께 작동해야 하는 라우터는 함수 포인터로 이루어진 구조체의 포인터를 받거나, 타입 태그를 기준으로 분기해야 하며, 호출자는 결과가 기록될 버퍼도 제공해야 합니다. C# 인터페이스 참조는 검사된 계약을 통해 동일한 대체 가능성을 제공합니다. 구현하는 클래스라면 무엇이든 전달할 수 있고, 하나의 클래스가 여러 인터페이스를 구현할 수도 있으며, 결과는 일반 관리 문자열입니다. 라우터는 특정 알림기를 직접 생성하는 대신 전달받은 인터페이스 객체를 호출해야 합니다.

인터페이스 기반 함수는 동일한 계약을 구현하는 서로 무관한 구현체를 받을 수 있습니다. 구체적인 타입에 따라 분기하는 대신 인터페이스 멤버를 호출하세요. 이 설계를 사용하면 라우터를 변경하지 않고도 호출자가 테스트 구현체나 새로운 알림기를 주입할 수 있습니다. 이 수업에서는 어떤 서비스에도 연결하지 않습니다.

C 참조

#include <stdio.h>

struct Notifier {
    void (*send)(const char *message, char *out, size_t size);
};

static void email_send(const char *message, char *out, size_t size) {
    snprintf(out, size, "email:%s", message);
}

static void route(const struct Notifier *notifier, const char *message) {
    char buffer[64];
    notifier->send(message, buffer, sizeof buffer);
    printf("%s\n", buffer);
}

int main(void) {
    struct Notifier email = { email_send };
    route(&email, "ok");
    return 0;
}

C# 보조 선언

interface IMeasure { int Measure(string value); }
class TextLength : IMeasure { public int Measure(string value) { return value.Length; } }

Main 내부의 C# 문장

IMeasure measure = new TextLength();
Console.WriteLine(measure.Measure("word"));

이 내용은 핵심만 다루는 학습용 발췌문입니다. 과제 파일에는 실행 가능한 완전한 래퍼가 포함되어 있으며, 위 코드 조각에는 관련 선언과 문장만 나와 있습니다.

참조 출력:

email:ok

C# 출력:

4
challenge icon

챌린지

쉬움

EmailNotifier.Send, SmsNotifier.Send 및 Router.Deliver를 구현하세요. Channel은 email 또는 sms입니다. 각 알림기는 해당 채널과 콜론을 접두사로 붙입니다. Router는 호출자가 제공한 모든 INotifier에 처리를 위임합니다. 이는 텍스트 형식을 지정하는 모델이며, 실제 네트워크 메시징은 아닙니다.

잠금 해제된 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 = input[0]; string before0=Snapshot(a0);
var a1 = input[1]; string before1=Snapshot(a1);
if (new EmailNotifier().Send("") != "email:" || new SmsNotifier().Send("x") != "sms:x" || Router.Deliver(new ProbeNotifier(),"x") != "custom:x") throw new Exception("Notifier 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);
}
}
class ProbeNotifier : INotifier { public string Send(string message) { return "custom:"+message; } }
quiz icon실력 점검

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

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

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