gpt4 book ai didi

c# - C# 中的 IComparable

转载 作者:太空狗 更新时间:2023-10-29 21:22:48 28 4
gpt4 key购买 nike

我有一个名为 Shape 的对象,它包含一个 public int[,] coordinate { get;放; 字段。

我有一个单独的类,它有一个 Shape 对象的集合。在特定点,我想检查:

if(shapes.Contains(shape))
{
// DoSomething
}

所以在 Shape 类中,我添加了 IComparable 引用并插入了 CompareTo 方法:

public int CompareTo(Shape other)
{
return this.coordinate.Equals(other.coordinate);
}

但是我收到一个错误:

Cannot implicitly convert type 'bool' to 'int'

因此,我该如何表述返回,以便它返回一个 int 而不是像现在这样返回一个 bool?

更新

如果我将返回代码更改为:

return this.coordinate.CompareTo(other.coordinate);

我收到以下错误消息:

Error 1 'ShapeD.Game_Objects.Shape' does not implement interface member 'System.IComparable.CompareTo(ShapeD.Game_Objects.Shape)'. 'ShapeD.Game_Objects.Shape.CompareTo(ShapeD.Game_Objects.Shape)' cannot implement 'System.IComparable.CompareTo(ShapeD.Game_Objects.Shape)' because it does not have the matching return type of 'int'. C:\Users\Usmaan\Documents\Visual Studio 2012\Projects\ShapeD\ShapeD\ShapeD\Game Objects\Shape.cs 10 18 ShapeD

最佳答案

IComparable 意味着,在某种意义上可以比较两个对象,您可以判断哪个对象具有“更高的值(value)”。它通常用于排序目的。您应该改写 Equals 方法。您还应该使用 Point 结构而不是数组。

class Shape : IEquatable<Shape>
{
public Point coordinate { get; set; }

public bool Equals(Shape other)
{
if (other == null) return false;
return coordinate.Equals(other.coordinate);
}

public override bool Equals(object other)
{
if (other == null) return false;
if (ReferenceEquals(this, other)) return true;
var shape = other as Shape;
return Equals(shape);
}

public override int GetHashCode()
{
return coordinate.GetHashCode()
}
}

关于c# - C# 中的 IComparable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18072425/

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