How to use foreach keyword on custom Objects in C#

后端 未结 3 472
鱼传尺愫
鱼传尺愫 2020-12-14 07:49

Can someone share a simple example of using the foreach keyword with custom objects?

3条回答
  •  死守一世寂寞
    2020-12-14 08:45

    From MSDN Reference:

    The foreach statement is not limited to IEnumerable types and can be applied to an instance of any type that satisfies the following conditions:

    has the public parameterless GetEnumerator method whose return type is either class, struct, or interface type, the return type of the GetEnumerator method has the public Current property and the public parameterless MoveNext method whose return type is Boolean.

    If you declare those methods, you can use foreach keyword without IEnumerable overhead. To verify this, take this code snipped and see that it produces no compile-time error:

    class Item
    {
        public Item Current { get; set; }
        public bool MoveNext()
        {
            return false;
        }
    }
    
    class Foreachable
    {
        Item[] items;
        int index;
        public Item GetEnumerator()
        {
            return items[index];
        }
    }
    
    Foreachable foreachable = new Foreachable();
    foreach (Item item in foreachable)
    {
    
    }
    

提交回复
热议问题