问题描述
我看到不同的行为,使用.Equals之间==两间.NET 4.0的新的记录<>实例。如果我已重写等于元组和LT的对象;>,并呼吁.Equals的元组的Equals的覆盖将被调用。如果我使用==上的元组的Equals的覆盖不叫。那是由设计和是否有意义?
I'm seeing different behavior between using .Equals and == between two of .NET 4.0's new Tuple<> instances. If I have overridden Equals on the object in the Tuple<> and call .Equals on the Tuples the override of Equals will be called. If I use == on the Tuples the override of Equals is not called. Is that by design and does it make sense?
编辑:从答复和意见,我可以告诉我没有说清楚。我知道,元组LT;>为引用类型和引用类型==将检查身份(的ReferenceEquals)。但是,应该元组LT;>覆盖==检查它包含的对象平等?为了保持一致性,可能不是。
From answers and comments I can tell I'm not being clear. I know Tuple<> is a reference type and that for reference types == will check identity (ReferenceEquals). But, should Tuple<> override == to check equality of the objects it contains? For consistency, probably not.
例如,如果我有一个简单的对象
For example if I have a simple object
public class NameAndNumber
{
public int Number { get; set; }
public string Name { get; set; }
public override bool Equals(object obj)
{
if (obj is NameAndNumber)
{
NameAndNumber other = (NameAndNumber)obj;
return Number == other.Number && Name == other.Name;
}
return false;
}
}
然后我做这样的事情:
and then I do something like this:
Tuple<NameAndNumber, NameAndNumber> left = new Tuple<NameAndNumber, NameAndNumber>(
new NameAndNumber { Name = "one", Number = 1 },
new NameAndNumber { Name = "two", Number = 2 });
Tuple<NameAndNumber, NameAndNumber> right = new Tuple<NameAndNumber, NameAndNumber>(
new NameAndNumber { Name = "one", Number = 1 },
new NameAndNumber { Name = "two", Number = 2 });
bool operatorResult = left == right;
bool equalsResult = left.Equals(right);
Console.Out.WriteLine("operatorResult = {0} equalsResult = {1}",
operatorResult, equalsResult);
我得到operatorResult =假equalsResult =真
I get operatorResult = false equalsResult = true
我应该期待什么?
我知道就NameAndNumber的Equals的实现不是正确的,它只是简化了样品code。
I know the implementation of Equals on NameAndNumber isn't "right" it's just simplified sample code.
我也曾尝试实施IEquatable,==,!=,并GetHash code。同样的结果。
I have also tried implementing IEquatable, ==, !=, and GetHashCode. Same results.
推荐答案
您看到来自结果设计妥协,元组现在F#和C#之间共享。主要的一点是,所有元组确实实现为引用类型,这不是那么明显了。
The results you see come from a design compromise, Tuples are now shared between F# and C#. The main point is that all Tuples are indeed implemented as reference types, that was not so obvious.
元组是否应该做深或浅的平等检查的决定被转移到两个接口: IStructuralComparable
, IStructuralEquatable
。请注意,这些2现在也由Array类实现的。
The decision whether Tuples should do deep or shallow equality checks was moved to two interfaces: IStructuralComparable
, IStructuralEquatable
. Note that those 2 are now also implemented by the Array class.
这篇关于这是预期的C#4.0元组的平等的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!