我想从电话簿中检索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
答案 0 :(得分:2)
您应该覆盖GetHashCode()
课程的Equals()
和PersonsName
。此链接可以帮助您:Use custom object as Dictionary Key
希望它有所帮助!