Tra*_*uer 6 c# performance gdi+ gethashcode
System.Drawing.Point
GetHashCode
如果你打算用它来描述图像/位图中的"像素",它有一个非常非常糟糕的方法:它只是X和Y坐标之间的XOR.
因此,对于具有2000x2000大小的图像,它具有荒谬的分数,因为只有对角线中的数字才具有相当好的散列.
GetHashCode
正如一些人已经在这里提到的那样,使用未经检查的乘法创建一个合适的方法非常容易.
但是我可以做些什么来使用这种改进的GetHashCode
方法HashSet
呢?我知道我可以创建自己的类/结构MyPoint
并使用这种改进的方法实现它,但是我会破坏我的项目中使用的所有其他代码片段System.Drawing.Point
.
是否可以System.Drawing.Point
使用某种扩展方法等"覆盖"该方法?或者"告诉" HashSet
使用另一个功能而不是GetHashCode
?
目前我正在使用SortedSet<System.Drawing.Point>
带有自定义IComparer<Point>
来存储我的积分.当我想知道该集是否包含Point I调用时BinarySearch
.它比HashSet<System.Drawing.Point>.Contains
具有10000个聚合的集合中的方法更快,但它没有像HashSet
好的哈希一样快.
Jar*_*ore 10
您可以创建自己的实现类IEqualityComparer<Point>
,然后将该类提供给HashSet
构造函数.
例:
public class MyPointEqualityComparer : IEqualityComparer<Point>
{
public bool Equals(Point p1, Point p2)
{
return p1 == p2; // defer to Point's existing operator==
}
public int GetHashCode(Point obj)
{
return /* your favorite hashcode function here */;
}
}
class Program
{
static void Main(string[] args)
{
// Create hashset with custom hashcode algorithm
HashSet<Point> myHashSet = new HashSet<Point>(new MyPointEqualityComparer());
// Same thing also works for dictionary
Dictionary<Point, string> myDictionary = new Dictionary<Point, string>(new MyPointEqualityComparer());
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
154 次 |
最近记录: |