2015年2月9日 星期一

[C#] IEnumerable 和 List

from: http://www.dotblogs.com.tw/city7/archive/2013/11/29/131970.aspx


因為 array 與 List<T> 都有實作 IEnumerable 介面,
將方法的引數宣告為 IEnumerable 便可通吃 array 與 List<T>,
如下:

int[] a = { 1, 2, 3 };
List<int> b = new List<int> { 4, 5, 6 };

ListAllElement(a);//可帶array
ListAllElement(b);//可帶List

---------------------------

private void ListAllElement(IEnumerable<int> elements)
{
    foreach (int element in elements)
    {
        Console.WriteLine(element);
    }
}


當然啦, 不只 List<T>, 只要是有實作 IEnumerable 介面的型別都適用。



其實我對於IEnumerable 的用途感受並不怎麼深,還是用比較明確的list吧 !


 

MangoHost Copyright © 2009 Cookiez is Designed by Ipietoon for Free Blogger Template