我正在使用地理编码API,需要将返回点的坐标表示为纬度/经度对.但是,我不确定是否为此使用结构或类.我最初的想法是使用一个结构,但它们似乎在C#中通常不赞成(例如,Jon Skeet 在这个答案中提到"我几乎从不定义自定义结构").性能和内存使用不是应用程序中的关键因素.
到目前为止,我已经基于一个简单的接口提出了这两个实现:
接口
public interface ILatLng
{
double Lat { get; }
double Lng { get; }
}
Run Code Online (Sandbox Code Playgroud)
LatLng类实现
public class CLatLng : ILatLng
{
public double Lat { get; private set; }
public double Lng { get; private set; }
public CLatLng(double lat, double lng)
{
this.Lat = lat;
this.Lng = lng;
}
public override string ToString()
{
return String.Format("{0},{1}", this.Lat, this.Lng);
}
public override bool Equals(Object obj)
{
if (obj == null)
return …Run Code Online (Sandbox Code Playgroud) 我基于我最近发现的性能特征Dictionary,所以我使用的Dictionary<type, bool>地方bool被忽略但据说我可以使用HashSet.
例如:
Dictionary<bounds, bool> overlap;
class bounds
{
public float top_left_x, top_left_y, width, height;
public bool equal(bounds other)
{
return upper_left_x + width > other.upper_left_x &&
upper_left_x < other.upper_left_x + other.width &&
upper_left_y + height > other.upper_left_y &&
upper_left_y < other.upper_left_y + other.height;
}
public ... GetHashCode()
{
...;
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我没有使用等于检查相等,而是重叠,这在其他地方一定会令人讨厌,但我有理由这样做.
我假设如果一个值可以在O(1)时间内从一个键中查找,那么一个键也可以从它自己查找.
所以我可能会把数千个边界重叠并做到这一点:
overlap.ContainsKey(new bounds(...));
Run Code Online (Sandbox Code Playgroud)
如果给定的绑定与集合中的任何其他绑定重叠,则在O(1)时间内找出.
我还想知道如果我改变一个边界的(x,y)位置会发生什么,大概就像删除然后再将它添加到集合中,性能明智,非常昂贵?
我将什么放入GetHashCode函数?
目标
如果这有效,那么我在使用这种机制后找出给定边界重叠的其他边界.
在这个系统中很少有边界移动,并且在填充集合后没有添加新的边界.新添加的边界需要能够重叠旧的边界.
结论
有关详细信息,请参阅下面的反馈.
总之,不可能实现O(1)性能,因为与默认等于不同,检查重叠是不可传递的.
然而,间隔树是一个很好的解决方案.