C# HashSet2 的工作方式与标准 C# HashSet 完全相同,无需编译

标签 c# collections xna hashset xbox

我正在使用字典创建自己的 HashSet,它作为标准 HashSet 工作。我这样做是因为 XNA XBox 的 C# 不支持 HashSet。

此代码基于我找到的示例中的代码。我已经编辑了示例来解决一些问题,但它仍然无法编译。

public class HashSet2<T> : ICollection<T>
{
    private Dictionary<T, Int16> dict;

    // code has been edited out of this example
    // see further on in the question for the full class

    public IEnumerator<T> GetEnumerator()
    {
        throw new NotImplementedException();
    }

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

.

'HashSet2<T>' does not implement interface member
'System.Collections.IEnumerable.GetEnumerator()'.
'HashSet2<T>.GetEnumerator()' cannot implement
'System.Collections.IEnumerable.GetEnumerator()'
because it does not have the matching return type of
'System.Collections.IEnumerator'

如果它的行为或它以可能意想不到的方式实现的偏差,我也很感激有关将其修复为更像标准 HashSet 的信息。

继续:stackoverflow.com/questions/9966336/c-sharp-xna-xbox-hashset-and-tuple

该类的最新版本:

public class HashSet2<T> : ICollection<T>
{
    private Dictionary<T, Int16> dict;
    // Dictionary<T, bool>

    public HashSet2()
    {
        dict = new Dictionary<T, short>();
    }

    public HashSet2(HashSet2<T> from)
    {
        dict = new Dictionary<T, short>();
        foreach (T n in from)
            dict.Add(n, 0);
    }

    public void Add(T item)
    {
        // The key of the dictionary is used but not the value.
        dict.Add(item, 0);
    }

    public void Clear()
    {
        dict.Clear();
    }

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

    public void CopyTo(
        T[] array,
        int arrayIndex)
    {
        throw new NotImplementedException();
    }

    public bool Remove(T item)
    {
        return dict.Remove(item);
    }

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

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

    public int Count
    {
        get {return dict.Keys.Count;}
    }

    public bool IsReadOnly
    {
        get {return false;}
    }
}

最佳答案

您想要枚举键,而不是字典。试试这个:

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

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

关于C# HashSet2 的工作方式与标准 C# HashSet 完全相同,无需编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10246572/

相关文章:

java - LinkedTransferQueue 线程安全吗?

c# - 以整数数组为键的字典

c# - 需要澄清有关 Action<T>

c# - 主要权限(属性)如何工作?

C# COM 互操作 : exposing function with a managed object as parameter

c# - 使用 MSpec(BDD 指南)对 ASP.NET MVC Controller 操作执行非常相似的规范

c# - 如何同时调用此构造函数和基本构造函数

java - 在java中将列表转换为逗号分隔字符串的最佳方法

c# - 在 XNA 游戏中无需拉伸(stretch)即可全屏显示

exception - 将 TextureAddressMode 设置为 Clamp for XNA Reach