c#等于,但不管订单如何
我是一个班级边缘,看起来像遵循
class Edge
{
public Node left { get; private set; }
public Node right { get; private set; }
public int Costs { get; private set; }
}
我想编写一个等式,无论订单如何,它都会返回真实。因此,当左边是“巴黎”,右为“ rom”时,我想返回true,如果它与右边的边缘进行比较,而右边是“巴黎”,而左则是“ rom”。
“ ROM”和“ PARIS”是节点类的名称。节点类只有一个名称的字段。
我试图写下自己的平等
public override bool Equals(object obj)
{
return obj is Edge edge &&
(EqualityComparer<Node>.Default.Equals(left, edge.left) || EqualityComparer<Node>.Default.Equals(right, edge.left)) &&
(EqualityComparer<Node>.Default.Equals(right, edge.right) || EqualityComparer<Node>.Default.Equals(right, edge.left));
}
,然后将边缘添加到边缘标题。
我对应该尝试的事情一无所知。
I hava a class Edge which looks like following
class Edge
{
public Node left { get; private set; }
public Node right { get; private set; }
public int Costs { get; private set; }
}
I want to write an equals which returns true regardless of the order. So when left is 'Paris' and right is 'Rom' I want to return true if it compares with an Edge where right is 'Paris' and left is 'Rom'.
'Rom' and 'Paris' are the names of the Node class. The node class just has a field for the name.
I tried to write my own equals like that
public override bool Equals(object obj)
{
return obj is Edge edge &&
(EqualityComparer<Node>.Default.Equals(left, edge.left) || EqualityComparer<Node>.Default.Equals(right, edge.left)) &&
(EqualityComparer<Node>.Default.Equals(right, edge.right) || EqualityComparer<Node>.Default.Equals(right, edge.left));
}
And I add edges to a HashSet of Edges.
I am little bit clueless about what I should try.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码检查一个边的
左
是否在左
或右边缘的
中的 是否对
一个边的值在左
或右
字段中。这可能会导致以下错误的equals()
检查:在这种情况下,您会找到一个“交叉”链接和一个“直线”链接,具体取决于您在哪里开始
equals()< /代码>来自。但是检查应既应该是“交叉”或“笔直”。
您可以在
equals()
方法中更改检查,如下:第一个块检查一个
左
是否转到另一个左
和一个右
转到另一个右
。第二个块检查“交叉”部分,其中一个左
转到另一个右
,一个右转到另一个左
。You code checks if the
left
value of one edge is in either theleft
orright
field of the other edge AND if theright
value of one edge is in either theleft
orright
field. This can lead to the following wrongEquals()
checks:In this case you will find one "cross" link and one "straight" link, depending on where you start your
Equals()
call from. But the checks should be either both "cross" or both "straight".You can change the checks in the
Equals()
method as follow:The first block checks if the one
Left
goes to the otherLeft
and the oneRight
goes to the otherRight
. The second block checks the "crossed" part, where oneLeft
goes to the otherRight
and the oneRight
goes to the otherLeft
.