Microsoft MVP성태의 닷넷 이야기
닷넷: 2374. C# - dynamic과 "Explicit Interface Implementation"의 문제 [링크 복사], [링크+제목 복사],
조회: 460
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12326정성태9/12/202022767개발 환경 구성: 516. Azure VM의 Network Adapter를 실수로 비활성화한 경우
12325정성태9/12/202021381개발 환경 구성: 515. OpenVPN - 재부팅 후 ICS(Internet Connection Sharing) 기능이 동작 안하는 문제
12324정성태9/11/202021863개발 환경 구성: 514. smigdeploy.exe를 이용한 Windows Server 2016에서 2019로 마이그레이션 방법
12323정성태9/11/202022250오류 유형: 649. Copy Database Wizard - The job failed. Check the event log on the destination server for details.
12322정성태9/11/202027068개발 환경 구성: 513. Azure VM의 RDP 접속 위치 제한 [1]
12321정성태9/11/202020321오류 유형: 648. netsh http add urlacl - Error: 183 Cannot create a file when that file already exists.
12320정성태9/11/202024460개발 환경 구성: 512. RDP(원격 데스크톱) 접속 시 비밀 번호를 한 번 더 입력해야 하는 경우
12319정성태9/10/202021851오류 유형: 647. smigdeploy.exe를 Windows Server 2016에서 실행할 때 .NET Framework 미설치 오류 발생
12318정성태9/9/202020773오류 유형: 646. OpenVPN - "TAP-Windows Adapter V9" 어댑터의 "Network cable unplugged" 현상
12317정성태9/9/202025089개발 환경 구성: 511. Beats용 Kibana 기본 대시 보드 구성 방법
12316정성태9/8/202023485디버깅 기술: 170. WinDbg Preview 버전부터 닷넷 코어 3.0 이후의 메모리 덤프에 대해 sos.dll 자동 로드
12315정성태9/7/202025609개발 환경 구성: 510. Logstash - FileBeat을 이용한 IIS 로그 처리 [2]
12314정성태9/7/202025307오류 유형: 645. IIS HTTPERR - Timer_MinBytesPerSecond, Timer_ConnectionIdle 로그
12313정성태9/6/202025523개발 환경 구성: 509. Logstash - 사용자 정의 grok 패턴 추가를 이용한 IIS 로그 처리
12312정성태9/5/202033315개발 환경 구성: 508. Logstash 기본 사용법 [2]
12311정성태9/4/202025895.NET Framework: 937. C# - 간단하게 만들어 보는 리눅스의 nc(netcat), json_pp 프로그램 [1]
12310정성태9/3/202023907오류 유형: 644. Windows could not start the Elasticsearch 7.9.0 (elasticsearch-service-x64) service on Local Computer.
12309정성태9/3/202021487개발 환경 구성: 507. Elasticsearch 6.6부터 기본 추가된 한글 형태소 분석기 노리(nori) 사용법
12308정성태9/2/202025472개발 환경 구성: 506. Windows - 단일 머신에서 단일 바이너리로 여러 개의 ElasticSearch 노드를 실행하는 방법
12307정성태9/2/202026357오류 유형: 643. curl - json_parse_exception / Invalid UTF-8 start byte
12306정성태9/1/202022410오류 유형: 642. SQL Server 시작 오류 - error code 10013
12305정성태9/1/202025081Windows: 172. "Administered port exclusions"이 아닌 포트 범위 항목을 삭제하는 방법
12304정성태8/31/202023906개발 환경 구성: 505. 윈도우 - (네트워크 어댑터의 우선순위로 인한) 열거되는 IP 주소 순서를 조정하는 방법
12303정성태8/30/202023632개발 환경 구성: 504. ETW - 닷넷 프레임워크 기반의 응용 프로그램을 위한 명령행 도구 etrace 소개
12302정성태8/30/202024274.NET Framework: 936. C# - ETW 관련 Win32 API 사용 예제 코드 (5) - Private Logger파일 다운로드1
12301정성태8/30/202022680오류 유형: 641. error MSB4044: The "Fody.WeavingTask" task was not given a value for the required parameter "IntermediateDir".
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...