为什么我没有例外? [英] why i dont get exception ?

查看:75
本文介绍了为什么我没有例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class First
    {
        string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public First(string _name)
        {
            
            name = _name;
        }
        public override int GetHashCode()
        {
            return name.GetHashCode();
        }
    }
    class Second
    {
        int id;
        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        public Second(int _id)
        {
            id = _id;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            First obj1 = new First("mohamed");
            First obj2 = new First("Ali");
            Second Nobj = new Second(1);
            Hashtable ht = new Hashtable();
            ht[obj1] = Nobj;
            ht[obj2]=Nobj;
            ht.Add(new First("mohamed"), Nobj);           
        }
    }



为什么当我两次输入值"mohmaed"时为什么没有得到异常?



why i dont get exception when i enter value "mohmaed" twice ??

推荐答案

Hashtable在对象上使用GetHashCode()方法.

First类被创建两次,并且GetHashCode()方法将返回2个不同的值(因为即使名称相同,内存中也存在两个不同的对象).
Hashtables use the GetHashCode() method on objects.

The First class is being created twice and the the GetHashCode() method will return 2 different values (because there are two different objects in memory, even when the names are the same).


[除了Mehdi的正确答案,解决方案1:]

另外,您应该理解,引入通用性时,早在.NET Framework v.2.0中就已经废弃了类System.Collections.Hashtable.相反,对于所有新开发,应使用类System.Collections.Generic.DictionarySystem.Collections.Generic.SortedDictionarySystem.Collections.Generic.SortedList;请参阅:
http://msdn.microsoft.com/en-us/library/system.collections. generic.aspx [ ^ ].

这些类别中的每一个都可以替换Hashtable,区别主要是数据冗余度和搜索算法速度之间的不同权衡.

—SA
[In addition to a correct answer by Mehdi, Solution 1:]

Also, you should understand that the class System.Collections.Hashtable was rendered obsolete as early as in .NET Framework, v.2.0, when generics were introduced. Instead, for all new development you should use the classes System.Collections.Generic.Dictionary, System.Collections.Generic.SortedDictionary or System.Collections.Generic.SortedList; please see:
http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx[^].

Each of these classes can replace Hashtable, the differences are mostly different trade-off between data redundancy and speed of search algorithms.

—SA


这篇关于为什么我没有例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆