怎么会是true

.Net技术 码拜 8年前 (2016-02-24) 885次浏览
怎么会这个结果  o3又没Add到字典里?为什么Console.WriteLine(dic.ContainsKey(o3));这个句在控制台上显示为true?什么道理?只不过构造函数采用和o1相同的参数值~!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace delete
{
class a
{
public int Id { get; private set; }
public a(int i)
{
Id = i;
}
public override bool Equals(object obj)
{
Console.WriteLine(“Equals”);
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return Id == ((a)obj).Id;
}
//返回余2的结果
public override int GetHashCode()
{
Console.WriteLine(“GetHashCode”);
return Id % 2;
}
}
class Program
{
static void Main(string[] args)
{
 var o1 = new a(1); //GetHashCode返回1
var o2 = new a(2); //GetHashCode返回0
var o3 = new a(1); //GetHashCode返回1
var dic = new Dictionary<a, object>();
dic.Add(o1, 123);
             Console.WriteLine(“分隔符”);
Console.WriteLine(dic.ContainsKey(o2));
Console.WriteLine(“分隔符”);
Console.WriteLine(dic.ContainsKey(o3));
}
}
}
解决方案

32

对于 a.GetHashCode() o1 和 o3 都返回 1
于是执行 a.Equals()
由于 var o3 = new a(1); 所以 return Id == ((a)obj).Id; 返回 true
原因是o1 和 o3 的 Id 相等

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明怎么会是true
喜欢 (0)
[1034331897@qq.com]
分享 (0)