从Dictionary中检索特定索引

时间:2017-02-06 05:47:59

标签: c# dictionary generics

我想从电话簿中检索Bill的电话号码。

class PersonsName
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

// Dictionary Class, add contacts to phone book
Dictionary<PersonsName, int> phoneBook = new Dictionary<PersonsName, int>()
{
    {new PersonsName {FirstName = "Bill", LastName = "Gates" }, 5550100 },
    {new PersonsName {FirstName = "Mark", LastName = "Zuckerberg" }, 5551438 }
};

为什么下面给我一个未找到密钥的例外情况?如何在不循环字典的情况下检索电话号码?

PersonsName personA = new PersonsName { FirstName = "Bill", LastName = "Gates" };
int billssNumber = phoneBook[personA]; //key not found

1 个答案:

答案 0 :(得分:2)

您应该覆盖GetHashCode()课程的Equals()PersonsName。此链接可以帮助您:Use custom object as Dictionary Key

希望它有所帮助!