Enable foreach for a class derived from a dictionary

I have a class derived from a dictionary. I need this class to simulate a HashSet because Silverlight does not know HashSets, and my classes use HashSets heavily. So I decided to exchange the HashSet for a dictionary. To further use my classes with all HashSet objects, I try to create my own HashSet class, which is derived from the dictionary and overrides all relavant methods, such as Add-method:

class HashSet<T> : Dictionary<T, object>
{

    public override void Add(T element)
    {
        base.Add(element, null);
    }
}

Now I need to enable foreach-loop for my new HashSet class. Obviously my class returns KeyValuePair in the foreach-loop, but I need T as the return type. Can someone tell me what and how do I need to override the dictionary base class?

Thanks in advance, Frank

+3
3

, Dictionary . . Dictionary, /, .

, :

public sealed class DictionaryBackedSet<T> : IEnumerable<T>
{
    private readonly Dictionary<T, int> dictionary = new Dictionary<T, int>();

    public IEnumerator<T> GetEnumerator()
    {
        return dictionary.Keys.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public bool Add(T item)
    {
        if (Contains(item))
        {
            return false;
        }
        dictionary.Add(item, 0);
        return true;
    }

    public bool Contains(T item)
    {
        return dictionary.ContainsKey(item);
    }

    // etc
}

:

public struct Empty {}

. - , :)

, System.Void (.. Dictionary<T, Void>), # : (

+15

, , , . HashSet .

+3

I think you will need to implement IEnumerable (Of T), which will work internally with the Keys collection.

IDictionary already implements IEnumerable (Of KeyValuePair (Of TKey, TValue)), but is it possible to implement it for another type too?

I'm with John trying to subclass a dictionary - avoid composition if you can - a much more suitable design pattern.

+2
source

Source: https://habr.com/ru/post/1716662/


All Articles