gpt4 book ai didi

c# - Int32.ToString() 太慢

转载 作者:可可西里 更新时间:2023-11-01 08:03:08 24 4
gpt4 key购买 nike

我有以下职位类别:

public struct Pos
{
public int x;
public int y;
public float height;

public Pos (int _x, int _y, float _height)
{
x = _x;
y = _y;
height = _height;
}

public override string ToString ()
{
return x.ToString() + "," + y.ToString();
}
}

但是因为我调用Pos.ToString()数千次,这对我来说太慢了。我所需要的只是一种基于 Pos.x 获取单个唯一值的有效方法和 Pos.y , 用作字典键。注意:我不能使用 Pos因为我正在比较 Pos 的不同实例仅仅xy .

最佳答案

All I need is an efficient way to get a single unique value based on Pos.x and Pos.y, for use as a dictionary key.

不要使用 ToString作为生成唯一字典键的方法,实现 IEquatable<Pos>反而。这样,您根本不必分配任何字符串来衡量相等性:

public struct Pos : IEquatable<Pos>
{
public int X { get; private set; }
public int Y { get; private set; }
public float Height { get; private set; }

public Pos(int x, int y, float height)
{
X = x;
Y = y;
Height = height;
}

public bool Equals(Pos other)
{
return X == other.X && Y == other.Y;
}

public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Pos && Equals((Pos) obj);
}

public override int GetHashCode()
{
unchecked
{
return (X*397) ^ Y;
}
}

public static bool operator ==(Pos left, Pos right)
{
return left.Equals(right);
}

public static bool operator !=(Pos left, Pos right)
{
return !left.Equals(right);
}
}

请注意,您可以删除 private set如果您使用的是 C#-6,则来自属性声明。

关于c# - Int32.ToString() 太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32375692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com