내용 보기
작성자
관리자 (IP : 172.17.0.1)
날짜
2021-01-18 08:50
제목
[C#] foreach에서 열거 변수의 타입을 var로 쓰면 object로 추론하는 문제
|
실제로 위의 글에 실린 예제에서 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?)
}
}
}
foreach (object item in bookcase)
{
Console.WriteLine(item.ISBN);
}
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(); } }
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();
}
}
using System.Linq; // Cast가 Linq의 확장 메서드이므로. foreach (var item in bookcase.Cast<Book>()) { Console.WriteLine(item.ISBN); } |
출처1
https://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&pageno=0&detail=1&wid=12490
출처2