哈希集
我有两个 hashset< t> 包含相同项目的集合(即对象的不同实例,但具有相同的值)。从我对 setequals 方法以下代码应返回true
,因为收集项目属性值是相等的,但是它返回false
:
var source = new HashSet<AllocatedComponent>()
{new AllocatedComponent() {
Weighting = 100,
ComponentId = 1,
Title = "Foo"}};
var destination = new HashSet<AllocatedComponent>()
{new AllocatedComponent() {
Weighting = 100,
ComponentId = 1,
Title = "Foo"}};
Console.WriteLine(source.SetEquals(destination)); // False
任何人都可以解释我'我在这里做错了吗?我的目标是检查两个集合是否包含相同数量的项目,并且具有相同的属性值。
我不太了解Microsoft文档的备注部分,因此可能会忽略一些显而易见的内容。
I have two HashSet<T> collections containing the same items (that is, different instances of the objects but with the same values). From my understanding of the SetEquals method the following code should return true
because the collection item property values are equal, but it returns false
:
var source = new HashSet<AllocatedComponent>()
{new AllocatedComponent() {
Weighting = 100,
ComponentId = 1,
Title = "Foo"}};
var destination = new HashSet<AllocatedComponent>()
{new AllocatedComponent() {
Weighting = 100,
ComponentId = 1,
Title = "Foo"}};
Console.WriteLine(source.SetEquals(destination)); // False
Can anyone please explain what I'm doing wrong here? My goal is to check that the two collections contain the same number of items, and with the same property values.
I don't quite understand the Remarks section of the Microsoft documentation so may be overlooking something quite obvious.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从第一个注释中,让框架使用其数据比较对象,您必须覆盖2种方法
bool equals(object O)
andint gethashcode()
。下面的代码给出了所需的结果(请注意,您必须将所有数据成员用于两个实现)As from the first comment to let the framework to compare the object using their data you have to override the 2 methods
bool Equals(object o)
andint GetHashCode()
. The code below gives the desired result (please note that you have to use all the data members for both the implementations)