foreach๋ฅผ ์ฌ์ฉํ ์ ์๋ ํด๋์ค๋ฅผ ๋ง๋๋ ๋ฐ ํ์ํ ๊ฒ์...
IEnumerable ์ธํฐํ์ด์ค๋ฅผ ์์ํด์ ํด๋์ค๋ฅผ ๋ง๋๋ ๊ฒ์ด๋ค.
์ผ๋ฐํ ํด๋์ค๋ IEnumerable ์ธํฐํ์ด์ค๋ฅผ ์์ํ๋ฉด ์ผ๋จ์ foreach๋ฅผ ํตํด ์ํํ ์ ์์ง๋ง,
์์๋ฅผ ์ํํ ๋๋ง๋ค ํ์ ๋ณํ์ ์ํํ๋ ์ค๋ฒ๋ก๋๊ฐ ๋ฐ์ํ๋ค๋ ๋ฌธ์ ์ ์ด ์๋ค.
(๊ธฐ๊ป ์ผ๋ฐํ๋ฅผ ํตํด ํ์ ๋ณํ์ ์ ๊ฑฐํ๋๋ foreach ๊ตฌ๋ฌธ์์ ํ์ ๋ณํ์ ์ผ์ผ์ผ ์ฑ๋ฅ์ ์ ํ์ํจ๋ค๋...)
System.Collections.Generic ๋ค์์คํ์ด์ค์ ์ด ๋ฌธ์ ๋ฅผ ํ ์ ์๋ ์ด์ ๊ฐ ์๋ค.
IEnumerable์ ์ผ๋ฐํ ๋ฒ์ ์ธ IEnumerable<T> ์ธํฐํ์ด์ค๊ฐ ๋ฐ๋ก ๊ทธ๊ฒ์ด๋ค.
์ด ์ธํฐํ์ด์ค๋ฅผ ์์ํ๋ฉด ํ์ ๋ณํ์ผ๋ก ์ธํ ์ฑ๋ฅ ์ ํ๊ฐ ์์ผ๋ฉด์๋
foreach ์ํ๊ฐ ๊ฐ๋ฅํ ํด๋์ค๋ฅผ ์์ฑํ ์ ์๋ค.
๋ค์์ IEnumerable<T> ์ธํฐํ์ด์ค์ ๋ฉ์๋์ด๋ค.
๋ฉ์๋ | ์ค๋ช |
IEnumerator GetEnumerator() | IEnumerator ํ์์ ๊ฐ์ฒด๋ฅผ ๋ฐํ(IEnumerable๋ก๋ถํฐ ์์๋ฐ์ ๋ฉ์๋) |
IEnumerator<T> GetEnumerator() | IEnumerator<T> ํ์์ ๊ฐ์ฒด๋ฅผ ๋ฐํ |
<์์ >
using System;
using System.Collections;
using System.Collections.Generic;
namespace EnumerableGeneric
{
class MainApp
{
class MyList<T> : IEnumerable<T>, IEnumerator<T>
{
private T[] array;
int position = -1;
public MyList()
{
array = new T[3];
}
public T this[int index]
{
get { return array[index]; }
set
{
if (index >= array.Length)
{
Array.Resize<T>(ref array, index + 1);
Console.WriteLine($"Array Resized : {array.Length}");
}
array[index] = value;
}
}
public int Length
{
get { return array.Length; }
}
public IEnumerator<T> GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
public T Current
{
get { return array[position]; }
}
object IEnumerator.Current
{
get { return array[position]; }
}
public bool MoveNext()
{
if(position==array.Length-1)
{
Reset();
return false;
}
position++;
return (position<array.Length);
}
public void Reset()
{
position = -1;
}
public void Dispose()
{
}
}
static void Main(string[] args)
{
MyList<string> strList = new MyList<string>();
strList[0] = "abc";
strList[1] = "def";
strList[2] = "ghi";
strList[3] = "jkl";
strList[4] = "mno";
foreach (var s in strList) Console.WriteLine(s);
Console.WriteLine();
MyList<int> intList = new MyList<int>();
intList[0] = 0;
intList[1] = 1;
intList[2] = 2;
intList[3] = 3;
intList[4] = 4;
foreach (var i in intList) Console.WriteLine(i);
Console.WriteLine();
}
}
}
<์์ ์ถ๋ ฅ>
Array Resized : 4
Array Resized : 5
abc
def
ghi
jkl
mno
Array Resized : 4
Array Resized : 5
0
1
2
3
4
'C# > ์ด๊ฒ์ด C#์ด๋ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์์ธ ์ฒ๋ฆฌํ๊ธฐ(2) System.Exception ํด๋์ค (0) | 2022.04.17 |
---|---|
60. ์์ธ ์ฒ๋ฆฌํ๊ธฐ(1) (0) | 2022.04.09 |
58. ์ผ๋ฐํ ์ปฌ๋ ์ (0) | 2022.02.28 |
57. ์ผ๋ฐํ ํ๋ก๊ทธ๋๋ฐ ์์ ๋ชจ์ (0) | 2022.02.28 |
56. ์ผ๋ฐํํ ๋, ํ์ ๋งค๊ฐ๋ณ์ ์ ์ฝ์ํค๊ธฐ (0) | 2022.02.28 |