Microsoft MVP성태의 닷넷 이야기
닷넷: 2374. C# - dynamic과 "Explicit Interface Implementation"의 문제 [링크 복사], [링크+제목 복사],
조회: 437
글쓴 사람
정성태 (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)
11337정성태10/24/201723984.NET Framework: 696. windbg - SOS DumpClass/DumpMT의 "Vtable Slots", "Total Method Slots", "Slots in VTable" 값에 대한 의미파일 다운로드1
11336정성태10/20/201725315.NET Framework: 695. windbg - .NET string의 x86/x64 메모리 할당 구조
11335정성태10/18/201724326.NET Framework: 694. 닷넷 - <Module> 클래스의 용도
11334정성태10/18/201724353디버깅 기술: 105. windbg - k 명령어와 !clrstack을 조합한 호출 스택을 얻는 방법
11333정성태10/17/201723526오류 유형: 422. 윈도우 업데이트 - Code 9C48 Windows update encountered an unknown error.
11332정성태10/17/201724036디버깅 기술: 104. .NET Profiler + 디버거 연결 + .NET Exceptions = cpu high
11331정성태10/16/201722302디버깅 기술: 103. windbg - .NET 4.0 이상의 환경에서 모든 DLL에 대한 심벌 파일을 로드하는 파이썬 스크립트
11330정성태10/16/201720506디버깅 기술: 102. windbg - .NET 4.0 이상의 환경에서 DLL의 심벌 파일 로드 방법 [1]
11329정성태10/15/201726395.NET Framework: 693. C# - 오피스 엑셀 97-2003 .xls 파일에 대해 32비트/64비트 상관없이 접근 방법파일 다운로드1
11328정성태10/15/201729769.NET Framework: 692. C# - 하나의 바이너리로 환경에 맞게 32비트/64비트 EXE를 실행하는 방법파일 다운로드1
11327정성태10/15/201723926.NET Framework: 691. AssemblyName을 .csproj에서 바꾼 경우 빌드 오류 발생하는 문제파일 다운로드1
11326정성태10/15/201722433.NET Framework: 690. coreclr 소스코드로 알아보는 .NET 4.0의 모듈 로딩 함수 [1]
11325정성태10/14/201723271.NET Framework: 689. CLR 4.0 환경에서 DLL 모듈의 로드 주소(Base address) 알아내는 방법
11324정성태10/13/201724658디버깅 기술: 101. windbg - "*** WARNING: Unable to verify checksum for" 경고 없애는 방법
11322정성태10/13/201724382디버깅 기술: 100. windbg - .NET 4.0 응용 프로그램의 Main 메서드에 Breakpoint 걸기
11321정성태10/11/201725033.NET Framework: 688. NGen 모듈과 .NET Profiler
11320정성태10/11/201726938.NET Framework: 687. COR_PRF_USE_PROFILE_IMAGES 옵션과 NGen의 "profiler-enhanced images" [1]
11319정성태10/11/201733833.NET Framework: 686. C# - string 배열을 담은 구조체를 직렬화하는 방법
11318정성태10/7/201725423VS.NET IDE: 122. 비주얼 스튜디오에서 관리자 권한을 요구하는 C# 콘솔 프로그램 제작 [1]
11317정성태10/4/201730714VC++: 120. std::copy 등의 함수 사용 시 _SCL_SECURE_NO_WARNINGS 에러 발생
11316정성태9/30/201727968디버깅 기술: 99. (닷넷) 프로세스(EXE)에 디버거가 연결되어 있는지 아는 방법 [4]
11315정성태9/29/201745934기타: 68. "시작하세요! C# 6.0 프로그래밍: 기본 문법부터 실전 예제까지" 구매하신 분들을 위한 C# 7.0/7.1 추가 문법 PDF [8]
11314정성태9/28/201726099디버깅 기술: 98. windbg - 덤프 파일로부터 닷넷 버전 확인하는 방법
11313정성태9/25/201724671디버깅 기술: 97. windbg - 메모리 덤프로부터 DateTime 형식의 값을 알아내는 방법파일 다운로드1
11312정성태9/25/201728074.NET Framework: 685. C# - 구조체(값 형식)의 필드를 리플렉션을 이용해 값을 바꾸는 방법파일 다운로드1
11311정성태9/20/201720107.NET Framework: 684. System.Diagnostics.Process 객체의 명시적인 해제 권장
... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...