这段代码为什么行不通 该怎么改进,关键是这个键怎么不在字典中呢,本人昨天想了很长时间,假如太复杂就不用写了 跟本人说一声太复杂就行了 能改的则帮本人改一改GetHashCode()用随机数法。谢谢了 尽量写的简单一点 让本人看明白就行了
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;
}
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;
}
static Random dd = new Random();
public override int GetHashCode()
{
Console.WriteLine(“GetHashCode”);
Id = dd.Next();
return Id ;
}
}
class Program
{
static void Main(string[] args)
{
var o1 = new a(1);
var o2 = new a(2);
var o3 = new a(1);
var dic = new Dictionary<a, object>();
dic.Add(o1, 123);
dic.Add(o3, 123);
Console.WriteLine(dic[o1].GetHashCode());
Console.WriteLine(dic[o3].GetHashCode());
Console.WriteLine(“分隔符”);
Console.WriteLine(dic.ContainsKey(o2));
Console.WriteLine(“分隔符”);
Console.WriteLine(dic.ContainsKey(o3));
Console.WriteLine(o3.GetType());
Console.WriteLine(dic[o3]);
}
}
}
解决方案
25