【发布时间】:2012-04-20 12:49:32
【问题描述】:
我正在创建自己的 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;}
}
}
【问题讨论】:
-
您可以提取 .NET 的参考源代码并使用它来帮助您完成项目。
-
有人告诉我,我在 SO 不能这样做。显然这与闭源有关。
-
@alan2here:您可以很好地查看 .NET 源代码。获取
ILSpy或Reflector或其他反汇编程序,打开 System.Core.dll 并浏览到 System.Collections.Generic.HashSet -
@MichaelJ.Gray 对我来说听起来不合法。但他可以使用 Mono 的 hashset,它在 MIT X11 下发布:github.com/mono/mono/blob/master/mcs/class/System.Core/…
-
我不想把它告诉大家,但是微软很久以前就发布了 .NET 框架的源代码......可以在 referencesource.microsoft.com/netframework.aspx 找到它,我都使用它我对 .NET 世界中的工作原理感到好奇的时候。
标签: c# collections xna hashset xbox