Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

C# - foreach에서 열거 변수의 타입을 var로 쓰면 object로 추론하는 문제

아래와 같은 질문이 있는데요,

var를 사용할 수 없는 이유가 궁금합니다!
; https://www.sysnet.pe.kr/3/0/5452

실제로 위의 글에 실린 예제에서 foreach 열거 변수의 타입을 var로 바꾸면,

using System;
using System.Collections;

class Book
{
    public long ISBN { get; set; }
    public string Writer { get; set; } = string.Empty;
    public string PublishingCompany { get; set; } = string.Empty;
}

class Bookcase : IEnumerable
{
    ArrayList _books = new ArrayList();
    public void Add(Book book)
    {
        _books.Add(book);
    }

    public IEnumerator GetEnumerator()
    {
        return _books.GetEnumerator();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var bookcase = new Bookcase();
        bookcase.Add(new Book()
        {
            ISBN = 9791158391805,
            Writer = "JungSeongtae",
            PublishingCompany = "wikibooks",
        });

        foreach (var item in bookcase)
        {
            Console.WriteLine(item.ISBN); // 컴파일 오류: Error CS1061 'object' does not contain a definition for 'ISBN' and no accessible extension method 'ISBN' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

        }
    }
}

해당 변수의 ISBN 필드를 접근하는 코드에서 컴파일 오류가 발생합니다. 즉, 위의 코드는 사실상 다음과 같이 인식되므로,

foreach (object item in bookcase)
{
    Console.WriteLine(item.ISBN);
}

당연히 object 타입의 ISBN 필드는 존재하지 않아 컴파일 오류가 발생하는 것입니다. 그리고, C# 컴파일러가 그런 식으로 추론할 수밖에 없는 이유는 IEnumerable 인터페이스로부터 어떠한 타입 정보도 얻을 수 없기 때문입니다.




따라서, 해결 방법은 타입 정보를 알 수 있는 IEnumerable<T> 인터페이스를 구현하면 되는 것입니다. 가령, 위의 Bookcase 타입은 다음과 같은 식으로 코드를 추가할 수 있습니다.

class Bookcase : IEnumerable<Book>
{
    List<Book> _books = new List<Book>();

    public void Add(Book book)
    {
        _books.Add(book);
    }

    public IEnumerator GetEnumerator()
    {
        return _books.GetEnumerator();
    }

    public IEnumerator<Book> GetEnumerator()
    {
        return _books.GetEnumerator();
    }
}

그런데, 저렇게 구현하면 동일한 이름의 GetEnumerator 메서드를 2개 정의한 것이므로 컴파일 오류가 발생합니다. 따라서, 최종적으로는 다음과 같이 IEnumerable의 GetEnumerator 버전을 숨기도록 "명시적인 인터페이스 구현" 방식을 사용해야 합니다.

class Bookcase : IEnumerable<Book>
{
    List<Book> _books = new List<Book>();

    public void Add(Book book)
    {
        _books.Add(book);
    }

    // 명시적인 인터페이스 구현으로 타입에서 IEnumerable 버전의 GetEnumerator() 메서드를 숨김 처리
    IEnumerator IEnumerable.GetEnumerator()
    {
        return _books.GetEnumerator();
    }

    // 따라서 C# 컴파일러는 IEnumerable<Book> 버전을 선택하므로 Book 타입 정보를 구함
    IEnumerator<Book> IEnumerable<Book>.GetEnumerator()
    {
        return _books.GetEnumerator();
    }
}

이후 다시 빌드하면 정상적으로 "var item"이 "Book item"으로 인식되는 것을 확인할 수 있습니다.

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




참고로, 만약 대상 타입이 소스 코드를 변경할 수 없는 경우라면 어떻게 해야 할까요?

어쩔 수 없습니다. 이런 경우는 확장 메서드를 사용해 IEnumerable<T>를 반환하는 별도의 메서드를 정의해 그걸 사용해야 합니다. 그리고 그런 확장 메서드는 이미 만들어진 것이 있으므로 그냥 다음과 같이 사용할 수 있습니다.

using System.Linq; // Cast가 Linq의 확장 메서드이므로.

foreach (var item in bookcase.Cast<Book>())
{
    Console.WriteLine(item.ISBN);
}




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/15/2021]

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

비밀번호

댓글 작성자
 



2021-01-15 11시08분
[예지] 상세한 답변 정말 감사드립니다~!!
[guest]

1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13423정성태10/6/20233078스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233220닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233247닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235348스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233107스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233784닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233351닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233161오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233641닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233407디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233598닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236873닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233380Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20234884닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233741닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233730Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233489닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233443VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20233869닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233396오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/20233223오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
13402정성태8/20/20233293닷넷: 2137. ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
13401정성태8/19/20233529닷넷: 2136. .NET 5+ 환경에서 P/Invoke의 성능을 높이기 위한 SuppressGCTransition 특성 [1]
13400정성태8/10/20233368오류 유형: 874. 파이썬 - pymssql을 윈도우 환경에서 설치 불가
13399정성태8/9/20233391닷넷: 2135. C# - 지역 변수로 이해하는 메서드 매개변수의 값/참조 전달
13398정성태8/3/20234155스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...