为foreach派生的类启用foreach

Aag*_*nor 3 c# inheritance dictionary

我有一个派生自Dictionary的类.我需要这个类来模拟HashSet,因为Silverlight不知道HashSets并且我的类大量使用HashSet.所以我决定用字典交换HashSet.为了进一步将我的类与所有HashSet-Objects一起使用,我尝试创建一个自定义的HashSet类,它派生自Dictionary并覆盖所有相关方法,如Add-method:

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

    public override void Add(T element)
    {
        base.Add(element, null);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我需要为我的新HashSet类启用foreach-loop.显然,我的类在foreach循环中返回一个KeyValuePair,但我需要T作为返回类型.谁能告诉我,我需要覆盖Dictionary基类的内容和方式?

先谢谢你,弗兰克

Jon*_*eet 15

我强烈建议你不要从头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
}
Run Code Online (Sandbox Code Playgroud)

您可能还想创建一个空结构作为字典的值类型参数:

public struct Empty {}
Run Code Online (Sandbox Code Playgroud)

这可能会节省一点内存.我现在不担心它 - 如果你编写字典而不是继承它,那么以后做出改变不会破坏任何东西:)

如果你可以System.Void用于此目的(即使用Dictionary<T, Void>),那将是很好的,但C#不会让你这样做:(