C# 每天溫習一點(IEnumerable


       1, IEnumerable<TSource> 多數屌絲寫成  IEnumerable<T>  無論TSource還是T都代表一個意思:要枚舉的對象的類型 。IEnumerable<T>是一個枚舉器,該枚舉器支持在指定類型的集合上進行簡單迭代(官方解釋),簡單的說就是實現了IEnumerable<T> 接口才能使用foreach 迭代。

       2,首先先看下如何實現自定義類的迭代。下面來看一段代碼。這里首先定義了一個Dog類,為該類添加了索引器和實現IEnumerable接口。實現的三大方法便可以foreach啦。通常我們在做類似自定義Session管理的時候會采用這樣設計思想。

      

  public class Dogs : IEnumerable, IEnumerator
    {
        public string name { get; set; }
        public bool sex { get; set; }
        public List<object> list = new List<object>();
        int dex = -1;
        /// <summary>
        /// 屌絲。這是一個索引器
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public object this[int index]
        {
            get
            {
                return list[index];
            }
            set
            {
                list[index] = value;
            }
        }
        public void Add<T>(T t)
        {
            list.Add(t);
        }
        public IEnumerator GetEnumerator()
        {
            return (IEnumerator)this;
        }
        public object Current
        {
            get { return this[dex]; }
        }
        public bool MoveNext()
        {
  if (dex >= list.Count-1)
            {
                return false;
            } dex
++; return true; } public void Reset() { dex = -1; } }

        這個關於Dogs的類有個索引器。所以它能存儲數據。它實現了IEnumerable so,他就能迭代了,是不是很神。

      

           string[] str = { "1", "2", "213" };
            Dogs dogs = new Dogs();
            foreach (var item in str)
            {
                dogs.Add(new Dogs()
                {
                    name = item,
                });
            }
            foreach (Dogs item in dogs)
            {
                Console.WriteLine(item.name);
            }

    二:接下來是一個奇奇怪怪的拓展方法:這個方法在字符串處理的時候的很好用,這個可以將一個實現了IEnumerable接口的類如 List<t>拼成字符串。是做前后端交互的必備。可以節省各位屌絲的大量時間。

   

       public static string ToSealString(this IEnumerable l, string split)
        {
            split = ",";
            StringBuilder strText = new StringBuilder();
            var e = l.GetEnumerator();
            while (e.MoveNext())
            {

                strText.Append(e.Current.ToString() + split);
            }
            if (strText.Length > 1)
            {
                strText = strText.Remove(strText.Length - split.Length, 1);
            }
            return strText.ToString();
        }

      ps:歡迎指正。補充,下班了,以后再補充。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM