Microsoft MVP성태의 닷넷 이야기
닷넷: 2374. C# - dynamic과 "Explicit Interface Implementation"의 문제 [링크 복사], [링크+제목 복사],
조회: 442
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - dynamic과 "Explicit Interface Implementation"의 문제

지난 글을 다루면서,

C# - dynamic 예약어 사용 시 런타임에 "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException" 예외가 발생하는 경우
; https://www.sysnet.pe.kr/2/0/14032

RuntimeBinderException 예외에 대해 검색해 보면 이런 글이 나옵니다.

Gotchas in dynamic typing
; https://csharpindepth.com/articles/DynamicGotchas

위의 글에서 첫 번째 항목이 "Explicit interface implementation"과 dynamic 호출의 문제를 다루고 있는데요, 이에 대해 간략하게 정리해 보겠습니다. ^^




우선, "Explicit interface implementation"은 인터페이스의 멤버를 명시적으로 구현한 경우를 일컫습니다. 관련해서 아래의 공식 문서에서 잘 설명하고 있는데요,

Explicit Interface Implementation
; https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/explicit-interface-implementation

문서에 포함된 코드를 보면,

public interface IControl
{
    void Paint();
}

public interface ISurface
{
    void Paint();
}

public class SampleClass : IControl, ISurface
{
    // Both ISurface.Paint and IControl.Paint call this method.
    public void Paint()
    {
        Console.WriteLine("Paint method in SampleClass");
    }
}

동일한 signature를 가진 Paint 메서드를 2개의 인터페이스에서 선언하고 있고, 그것을 SampleClass에서 구현하고 있습니다. 그래서 다음과 같이 사용할 수 있는데요,

internal class Program
{
    static void Main(string[] args)
    {
        IControl inst1 = new SampleClass();
        inst1.Paint();

        ISurface inst2 = new SampleClass();
        inst2.Paint();
    }
}

어떤 경우에는 저게 의도한 구현일 수 있지만, 또 다른 경우에는 인터페이스마다 구현을 달리하고 싶을 수도 있습니다. 즉, 이렇게 나누고 싶은 경우인데요,

public class SampleClass : IControl, ISurface
{
    void IControl.Paint()
    {
        System.Console.WriteLine("IControl.Paint");
    }

    void ISurface.Paint()
    {
        System.Console.WriteLine("ISurface.Paint");
    }
}

바로 저렇게 (public 접근 제한자를 생략하고) "[Interface].[메서드명]" 형태로 구현하는 것을 두고 "Explicit interface implementation"이라고 부릅니다. 이렇게 정의한 메서드의 대표적인 특징은, 반드시 해당 인터페이스 타입으로 캐스팅한 후에만 호출할 수 있다는 점입니다.

SampleClass inst3 = new SampleClass();
inst3.Paint(); // 컴파일 오류: "Explicit interface implementation" 메서드는 직접 호출할 수 없습니다.

IControl control = inst3 as IControl;
control.Paint(); // 올바른 호출: IControl.Paint 메서드가 호출됩니다.

ISurface surface = inst3 as ISurface;
surface.Paint(); // 올바른 호출: ISurface.Paint 메서드가 호출됩니다.




이러한 명시적 인터페이스 구현이 dynamic 호출과 연관이 되는데요, 즉 다음과 같이 dynamic으로 변환한 인스턴스에 대해서는 "Explicit interface implementation" 메서드를 호출할 수 없다는 제약이 있습니다.

dynamic inst = new SampleClass();
inst.Paint(); // 예외 발생
              // Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'ConsoleApp3.SampleClass' does not contain a definition for 'Paint'

이에 대해 "Gotchas in dynamic typing" 글의 재현 코드에서는 ICollection이 구현된 System.Array 타입으로도 설명하고 있는데요,

System.Array arr = new int[] { 1, 2, 3 };
ICollection<int> coll = arr as ICollection<int>;
Console.WriteLine(coll.Count); // 출력 결과: 3

dynamic dnArr = arr;
Console.WriteLine(dnArr.Count); // 예외 발생
                                // Unhandled exception. Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.Array' does not contain a definition for 'Count'

실제로 System.Array의 소스 코드를 살펴보면,

// https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Array.cs#L1011

[Serializable]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract partial class Array : ICloneable, IList, IStructuralComparable, IStructuralEquatable
{
    internal Array() { }
    // ...[생략]...

    // Number of elements in the Array.
    int ICollection.Count => Length;

    // ...[생략]...
}

명시적인 인터페이스 구현을 확인할 수 있습니다. 참고로, "Gotchas in dynamic typing" 글에서는 이 사례가 C# 타입 시스템과 동적 형식 체계 간의 대표적인 "impedance mismatch"라고 언급하고 있습니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




이 외에도 "Gotchas in dynamic typing" 글에서는 "Overloading ambiguity", "Compound assignment", "Anonymous types", "Generics" 및 WCF와 관련된 dynamic 문제들을 다루고 있으니 가볍게 살펴보시면 좋을 것 같습니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/22/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11394정성태12/8/201722270개발 환경 구성: 342. 비주얼 스튜디오에서 실행하던 ASP.NET Core (.NET Framework) 응용 프로그램을 명령행에서 실행하는 방법
11393정성태12/7/201727929Windows: 145. 윈도우 10 빌드 17046부터 WSL에서 백그라운드 작업 지원 [5]
11392정성태12/7/201721716개발 환경 구성: 341. openSUSE에 닷넷 코어 설치
11391정성태12/7/201725278개발 환경 구성: 340. WSL을 이용해 윈도우 PC 1대에서 openSUSE 응용 프로그램을 Visual Studio로 개발하는 방법 [1]
11390정성태12/7/201734003개발 환경 구성: 339. WSL을 이용해 윈도우 PC 1대에서 Linux 응용 프로그램을 Visual Studio로 개발하는 방법 [6]
11389정성태12/7/201723258오류 유형: 440. .NET Core 오류 - 0x80131620 Unable to load DLL 'libuv'
11388정성태12/6/201726912개발 환경 구성: 338. WSL 또는 Ubuntu에 닷넷 코어 설치 [3]
11387정성태12/6/201725854오류 유형: 439. 이벤트 로그 - Data Sharing Service 서비스의 %%3239247874 오류 메시지
11386정성태12/5/201723237오류 유형: 438. Hyper-V - '...' failed to add device 'Virtual CD/DVD Disk'
11385정성태12/5/201736299VC++: 121. DXGI를 이용한 윈도우 화면 캡처 소스 코드(Visual C++) [16]파일 다운로드1
11384정성태12/5/201725486오류 유형: 437. Visual C++ - Cannot open include file: 'SDKDDKVer.h'
11383정성태12/4/201727478디버깅 기술: 110. 비동기 코드 실행 중 예외로 인한 ASP.NET 프로세스 비정상 종료 현상 [1]
11382정성태12/4/201726991오류 유형: 436. System.Data.SqlClient.SqlException (0x80131904): Connection Timeout Expired 예외 발생 시 "[Pre-Login] initialization=48; handshake=1944;" 값의 의미
11381정성태11/30/201724596.NET Framework: 702. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법(두 번째 이야기)파일 다운로드1
11380정성태11/30/201724254디버깅 기술: 109. windbg - (x64에서의 인자 값 추적을 이용한) Thread.Abort 시 대상이 되는 스레드를 식별하는 방법
11379정성태11/30/201722816오류 유형: 435. System.Web.HttpException - Session state has created a session id, but cannot save it because the response was already flushed by the application.
11378정성태11/29/201724892.NET Framework: 701. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법 [1]파일 다운로드1
11377정성태11/29/201725079.NET Framework: 700. CommonOpenFileDialog 사용 시 사용자가 선택한 파일 목록을 구하는 방법 [3]파일 다운로드1
11376정성태11/28/201730350VS.NET IDE: 123. Visual Studio 편집기의 \r\n (crlf) 개행을 \n으로 폴더 단위로 설정하는 방법
11375정성태11/28/201723136오류 유형: 434. Visual Studio로 ASP.NET 디버깅 중 System.Web.HttpException - Could not load type 오류
11374정성태11/27/201729412사물인터넷: 14. 라즈베리 파이 - (윈도우의 NT 서비스처럼) 부팅 시 시작하는 프로그램 설정 [1]
11373정성태11/27/201729184오류 유형: 433. Raspberry Pi/Windows 다중 플랫폼 지원 컴파일 관련 오류 기록
11372정성태11/25/201730841사물인터넷: 13. 윈도우즈 사용자를 위한 라즈베리 파이 제로 W 모델을 설정하는 방법 [4]
11371정성태11/25/201724794오류 유형: 432. Hyper-V 가상 스위치 생성 시 Failed to connect Ethernet switch port 0x80070002 오류 발생
11370정성태11/25/201725514오류 유형: 431. Hyper-V의 Virtual Switch 생성 시 "External network" 목록에 특정 네트워크 어댑터 항목이 없는 경우
11369정성태11/25/201726720사물인터넷: 12. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드 및 마우스로 쓰는 방법 (절대 좌표, 상대 좌표, 휠) [1]
... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...