简体   繁体   中英

Implementing IEnumerable in C#

I'm creating a class named MyDictionary which works as the dictionary class and which implements interfaces like IEnumerable , ICollection and IDictionary . I've manually created the interfaces and manually wrote the functionality of each method in the interface except for the IEnumerable , I can't think of what methods that I can implement for the IEnumerable interface, can someone tell me what methods I can implement for the class I'm working on ?

Here's the code:

using System;
using System.Collections;
using System.Collections.Generic;

namespace lab3
{ 
    interface ICollection 
    {
        int Count { get; }
        
        int enqueue(object value);
        void dequeue(object value);
        //void CopyTo(Array array, int index);
    }
    
    interface IEnumerable 
    {
        IEnumerator GetEnumerator();
    }
    
    interface IDictionary 
    {
        bool Contains(object key);
        Boolean TryGetIndexOfKey(Object key, out Int32 index);
        void Remove(object key);
        void Add(object key, object value);
    }
    
    class MyDictionary : IEnumerable, IDictionary, ICollection
    {
        private DictionaryEntry[] items;
        private Int32 ItemsInUse = 0;
        Int32 index = -1;
  
        public MyDictionary(Int32 numItems)
        {
            items = new DictionaryEntry[numItems];
        }
        
        public bool Contains(object key)
        {
            Int32 index;
            return TryGetIndexOfKey(key, out index);
        }
        
        public Boolean TryGetIndexOfKey(Object key, out Int32 index)
        {
            for (index = 0; index < ItemsInUse; index++)
            {
                // If the key is found, return true (the index is also returned).
                if (items[index].Key.Equals(key)) return true;
            }
  
            // Key not found, return false (index should be ignored by the caller).
            return false;
        }
        
        public void Add(object key, object value)
        {
            // Add the new key/value pair even if this key already exists in the dictionary.
            if (ItemsInUse == items.Length)
                throw new InvalidOperationException("The dictionary cannot hold any more items.");
            items[ItemsInUse++] = new DictionaryEntry(key, value);
        }
        
        public void Remove(object key)
        {
            if (key == null) throw new ArgumentNullException("key");
            // Try to find the key in the DictionaryEntry array
            Int32 index;
            
            if (TryGetIndexOfKey(key, out index))
            {
                // If the key is found, slide all the items up.
                Array.Copy(items, index + 1, items, index, ItemsInUse - index - 1);
                ItemsInUse--;
            }
            else
            {
                // If the key is not in the dictionary, just return.
            }
        }   
        
        public int Count { get { return ItemsInUse; } }

        public void dequeue(object value)
        {
            
        }

        public int enqueue(object value)
        {
            return -1;
        }
  
        GetEnumerator()
        {
            // Construct and return an enumerator.
            return (IEnumerator) GetEnumerator();
        }
    }

    class Program
    {
        static void Main(string[] args)
        { 
            dictionary.Add("Mohammed", 21);
            dictionary.Remove("Mohammed");
            Console.WriteLine("Number of elements in dictionary = {0}", dictionary.Count);
            Console.WriteLine("Does dictionary contain 'Mohammed'? {0}", 
            dictionary.Contains("Mohammed"));
        }
    }
}

Typically a IEnumerable interface have a single method that returns a IEnumerator , just as in your example.

You do not define the IEnumerator interface, but it would typically look like this

interface IMyEnumerator{
    bool MoveNext();
    object Current {get;}
}

The implementation of this interface could for example contain an array and an index. MoveNext() increments the index and returns true if the current index is smaller than the array length. Current would just return the array value for the index. Note that this should be a separate class from MyDictionary , do not try to make a single class implement both IEnumerable and IEnumerator .

The language have various features to make it easier to use the built in IEnumerable<T> interface, like foreach loops and iterator blocks . So it is fairly rare to write your own IEnumerator from scratch, but it is worth knowing how it works under the hood.

I would also note that your ICollection interface looks like a queue, in contrast to the build in ICollection<T> interface. And I find it a bit odd for a class to implement both a dictionary interface and a queue interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM