Microsoft MVP성태의 닷넷 이야기
닷넷: 2374. C# - dynamic과 "Explicit Interface Implementation"의 문제 [링크 복사], [링크+제목 복사],
조회: 455
글쓴 사람
정성태 (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)
12376정성태10/15/202020422오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
12375정성태10/15/202021597Windows: 177. 윈도우 탐색기에서 띄우는 cmd.exe 창의 디렉터리 구분 문자가 'Yen(&#0165;)' 기호로 나오는 경우 [1]
12374정성태10/14/202029393.NET Framework: 953. C# 9.0 - (6) 함수 포인터(Function pointers) [1]파일 다운로드2
12373정성태10/14/202020516.NET Framework: 952. OpCodes.Box와 관련해 IL 형식으로 직접 코딩 시 유의할 점
12372정성태10/13/202026002.NET Framework: 951. C# 9.0 - (5) 로컬 함수에 특성 지정 가능(Attributes on local functions)파일 다운로드1
12371정성태10/13/202024823개발 환경 구성: 519. Visual Studio의 Ctrl+Shift+U (Edit.MakeUppercase) 단축키가 동작하지 않는 경우
12370정성태10/13/202022474Linux: 33. Linux - nmcli를 이용한 고정 IP 설정
12369정성태10/12/202026308Windows: 176. Raymond Chen이 한글날에 밝히는 윈도우의 한글 자모 분리 현상 [3]
12368정성태10/12/202024934오류 유형: 668. VSIX 확장 빌드 - The "GetDeploymentPathFromVsixManifest" task failed unexpectedly.
12367정성태10/12/202035357오류 유형: 667. Ubuntu - Temporary failure resolving 'kr.archive.ubuntu.com' [2]
12366정성태10/12/202026502.NET Framework: 950. C# 9.0 - (4) 원시 크기 정수(Native ints) [1]파일 다운로드1
12365정성태10/12/202025282.NET Framework: 949. C# 9.0 - (3) 람다 메서드의 매개 변수 무시(Lambda discard parameters)파일 다운로드1
12364정성태10/11/202025176.NET Framework: 948. C# 9.0 - (2) localsinit 플래그 내보내기 무시(Suppress emitting localsinit flag)파일 다운로드1
12363정성태10/11/202026064.NET Framework: 947. C# 9.0 - (1) 대상으로 형식화된 new 식(Target-typed new expressions) [2]파일 다운로드1
12362정성태10/11/202023083VS.NET IDE: 151. Visual Studio 2019에 .NET 5 rc/preview 적용하는 방법
12361정성태10/11/202026205.NET Framework: 946. C# 9.0을 위한 개발 환경 구성
12360정성태10/8/202018627오류 유형: 666. The type or namespace name '...' does not exist in the namespace 'Microsoft.VisualStudio.TestTools' (are you missing an assembly reference?)
12359정성태10/7/202021221오류 유형: 665. Windows - 재부팅 후 iSCSI 연결이 끊기는 문제
12358정성태10/7/202024083오류 유형: 664. Web Deploy 설치 시 "A newer version of Microsoft Web Deploy 3.6 was found on this machine." 오류 [3]
12357정성태10/7/202021448오류 유형: 663. 이벤트 로그 - The storage optimizer couldn't complete retrim on New Volume
12356정성태10/7/202036970오류 유형: 662. ASP.NET Core와 500.19, 500.21 오류 (0x8007000d)
12355정성태10/3/202019403오류 유형: 661. Hyper-V Linux VM의 Internal 유형의 가상 Switch에 대한 IP 연결이 되지 않는 경우
12354정성태10/2/202034755오류 유형: 660. Web Deploy (msdeploy.axd) 실행 시 오류 기록 [1]
12353정성태10/2/202022321개발 환경 구성: 518. 비주얼 스튜디오에서 IIS 웹 서버로 "Web Deploy"를 이용해 배포하는 방법
12352정성태10/2/202025128개발 환경 구성: 517. Hyper-V Internal 네트워크에 NAT을 이용한 인터넷 연결 제공
12351정성태10/2/202022873오류 유형: 659. Nox 실행이 안 되는 경우 - Unable to bind to the underlying transport for ...
... 61  62  63  64  65  66  [67]  68  69  70  71  72  73  74  75  ...