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


    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));
     
            }
        }
    }

  • 相关阅读:
    IE浏览器兼容问题
    sublime text3插件和快捷键
    CSS3高级
    盒子模型
    css3动画
    FreeBSD port安装 *** [checksum] Error code 1
    vs 2008设置vs6.0字体
    android 无法读取lua文件问题2
    u盘安装centos6 x8664
    cocos2dx lua 路径问题的一个bug (网络整理)
  • 原文地址:https://www.cnblogs.com/siso/p/3692491.html
Copyright © 2020-2023  润新知