首页 > 其他 > 详细

C# GetHashCode与Equals在HashTable表查找时的关系

时间:2014-04-29 01:36:15      阅读:403      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.Threading;
using System.IO;
using System.Security.Cryptography;
using Common;
 
 
namespace ConsoleApplication2
{
    public class Test
    {
        private string _id;
 
        public string Id
        {
            get { return _id; }
            set { _id = value; }
        }
 
        public Test(string id)
        {
            _id = id;
        }
 
        public override int GetHashCode()
        {
            Console.WriteLine("GetHashCode()");         
            return Id.Length;
        }
 
        public override bool Equals(object obj)
        {
            Console.WriteLine("Equals()");
            return Id == (obj as Test).Id;
        }
    }
 
    class Program
    {
        /// <summary>
        /// 如果GetHashCode相等则不用Equals了,否则需要Equals
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            Dictionary<Test, string> dc = new Dictionary<Test, string>();
 
            Test t1 = new Test("a");
            Test t2 = new Test("b");
            Test t3 = new Test("cc"); 
 
            dc.Add(t1, "");
            Console.WriteLine("----------------");
            Console.WriteLine(dc.ContainsKey(t1));
            Console.WriteLine("----------------");
            Console.WriteLine(dc.ContainsKey(t2));
            Console.WriteLine("----------------");
            Console.WriteLine(dc.ContainsKey(t3));
 
        }
    }
}
bubuko.com,布布扣

bubuko.com,布布扣

C# GetHashCode与Equals在HashTable表查找时的关系,布布扣,bubuko.com

C# GetHashCode与Equals在HashTable表查找时的关系

原文:http://www.cnblogs.com/siso/p/3692491.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!