C# HashSet2 to work exactly like the standard C# HashSet, not compiling

人走茶凉 提交于 2019-12-06 07:27:51

You want to enumerate the keys, not the dictionary. Try this:

public IEnumerator GetEnumerator()
{
    return ((IEnumerable)dict.Keys).GetEnumerator();
}

IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
    return ((IEnumerable<T>)dict.Keys).GetEnumerator();
}

The point is that the HashSet's GetEnumerator returns enumerator that enumerates keys of type T while dictionary's GetEnumerator returns enumerator that enumerates KeyValue object.

UPDATE

Change it to below:

public IEnumerator GetEnumerator()
{
    dict.Keys.GetEnumerator();
}

IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
    return dict.Keys.GetEnumerator();
}

You can simply use Mono's HashSet<T>. You might need to make some minor changes to #if, or remove some interfaces/attributes, but it works on .net.

It's using the MIT X11 license, which is permissive. https://github.com/mono/mono/blob/master/mcs/class/System.Core/System.Collections.Generic/HashSet.cs

Just took a look at the source, and all implementations of GetEnumerator in the Dictionary<TKey, TValue> return the KeyCollection.Enumerator/ValueCollection.Enumerator objects instead of IEnumerator<T> (which is what we need). The good news is that the Key/ValueCollation.Enumerator implement both System.Collection.IEnumerator and IEnumerator<T> interfaces, so you can safely cast to those types.

Try doing this instead:

public IEnumerator GetEnumerator()
{
    return (IEnumerator)dict.Keys.GetEnumerator();
}

IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
    return (IEnumerator<T>)dict.Keys.GetEnumerator();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!