new People { { "rr", "ss" } }是什麼?

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/ashcn2001/article/details/72123064

var x = new People { { “rr”, “ss” } } 創建了一個新的class實例,但爲什麼沒有加上(),測試了一下 原來他實現了IEnumerable:如下

        class People : System.Collections.IEnumerable
        {
            public IEnumerator GetEnumerator()
            {
                throw new NotImplementedException();
            }

            public void Add(string key, object value) {
            }
        }
        static void Main(string[] args)
        {

            var x = new People { { "rr", "ss" } };
        }

這樣就不會報錯了,但是 這個並不是完整的結構,我們舉個完整結構的例子

 public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Person(string firstName, string lastName)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
        }
    }

另外通過People類來實現IEnumerable和IEnumerator接口.

//實現IEnumerable接口

public class People :IEnumerable

{

   public Person [] pers;

   public People(Person [] ps)

    {

      this.pers = ps;

    }

    public IEnumerator GetEnumerator()

    {

         //foreach(Person p in pers)

         // {

             //  yield return p;

          // }

      return new People1(pers);

      }

}

  //實現IEnumerator接口

   public class People1 : IEnumerator
    {
        public Person[] pers;
        public People1(Person[] per)
        {
            this.pers = per;
        }
        int position = -1;

        public bool MoveNext()
        {
            position++;
            return position < pers.Length;
        }
        public void Reset()
        {
            position=-1;
        }
        public object Current
        {
            get
            {
               try
               {
                   return pers[position];
               }
                catch(IndexOutOfRangeException ex)
                {
                    throw new InvalidOperationException();
                }
            }
        }
    }

附錄

public interface IEnumerable
{
      //IEnumerable只有一個方法,返回可循環訪問集合的枚舉數。
      IEnumerator GetEnumerator()  ;
}


public interface IEnumerator
{  
      // 方法
      //移到集合的下一個元素。如果成功則返回爲 true;如果超過集合結尾,則返回false。
      bool MoveNext();
     // 將集合設置爲初始位置,該位置位於集合中第一個元素之前
      void Reset();

      // 屬性:獲取集合中的當前元素
      object Current { get; }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章