博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
GetHashCode 与HashTable ,Dictionary
阅读量:7265 次
发布时间:2019-06-29

本文共 2692 字,大约阅读时间需要 8 分钟。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Text.RegularExpressions;using System.IO;using System.Collections;using Data = System.Data.SqlClient;namespace COL_TEST{    class Program    {        static void Main(string[] args)        {            //一个对象的 GetHashCode 方法必须总是返回同一个哈希代码            //Console.WriteLine(ht.GetHashCode());            //Console.WriteLine(ht.GetHashCode());            A a = new A(2, 2);            A aa = new A(1, 4);            A bb = new A(1, 3);            Dictionary
hs = new Dictionary
(); hs.Add(a, 2); hs.Add(aa, 2); hs.Add(bb, 2); foreach (KeyValuePair
p in hs) { Console.WriteLine("Key: " + p.Key + " Value: " + p.Value); Console.WriteLine("hashCode:{0}", p.Key.GetHashCode()); } Console.WriteLine("-----------------"); /***************/ Hashtable hht = new Hashtable(); Class3 cc = new Class3(2, 3); Class3 cc2 = new Class3(1, 4); Class3 cc3 = new Class3(3, 3); hht.Add(cc, "test1"); hht.Add(cc2, "test2"); hht.Add(cc3, "test3"); //cc.x = 5; //如果修改cc的状态,会导致cc遍历不到 foreach (var item in hht.Keys) { Console.WriteLine(item.ToString()); Console.WriteLine(hht[item]); } Console.Read(); //如果将一个引用类型的数据加入到hashTable中,首先会调用该类型的GetHashCode方法,返回的键值为重写toString 方法返回值 // } } public struct MyStruct { public int _sx; public string _msg; public int _id; public DateTime _epoch; } class A { int i, j; public A(int i, int j) { this.i = i; this.j = j; } public override Int32 GetHashCode() { return i * j; } public override string ToString() { return String.Format("({0},{1})", i, j); } } class Class3 { public int x; int y; public Class3(int x, int y) { this.x = x; this.y = y; } public override int GetHashCode() { Console.WriteLine("判断hashcode"); return x + y; } public override bool Equals(object obj) { Console.WriteLine("判断equals"); return base.Equals(obj); } public override string ToString() { return x.ToString() + y.ToString(); } } }

转载于:https://www.cnblogs.com/voidobject/archive/2012/11/06/3975488.html

你可能感兴趣的文章
equals hashCode
查看>>
stub 测试接口说明
查看>>
C#实现所有经典排序算法
查看>>
HBase源码阅读资源
查看>>
Mockito自定义verify参数Matcher
查看>>
mysql主从同步(低版本)参数说明
查看>>
webmin的安装
查看>>
Windows Server 2012 R2 里面如何安装Net Framework 3.5
查看>>
junit浅学笔记一
查看>>
MS SQL 完全卸载数据库
查看>>
定制controller转场动画
查看>>
J2me流媒体技术实现讨论[1]
查看>>
IOS项目之弹出动画三
查看>>
javascript显式类型转换
查看>>
【分享】Matlab R2015a 发布啦!
查看>>
怎样正确查看Linux的内存占用情况
查看>>
Mysql第六天 查询 1
查看>>
php扩展中如何定义线程安全的全局对象
查看>>
hdu 2084 数塔
查看>>
Struts2获取web对象的4种方式
查看>>