Good afternoon. I have a strange problem. When iterating through the list, SortedDictionary does not recognize the key. Namely, it gives out that the key was not found. System.Collections.Generic.KeyNotFoundException
此外,只有当向列表中添加2个以上的元素时才会发出错误。同时,如果3个元素在1号上是错误的,如果5个元素在1号和3号上,4个元素在1号上。
public: Collections::Generic::SortedDictionary<Product_for_sale^, int> products;
void Score:: setProductsLabel() {
int y = 50;
productLabels.Clear();
for each (Product_for_sale ^ key in products.Keys) {
String^ product_by_score = "";
System::Windows::Forms::Label^ info = (gcnew System::Windows::Forms::Label());
if (products[key] > 0) {
product_by_score = key->getName() + " | " + products[key] +
" | " + key->getFullPrice() * products[key] + "\n";
info->BackColor = System::Drawing::Color::Red;
}
else {
info->BackColor = System::Drawing::Color::PaleGreen;
product_by_score = key->getName() + " | " + "СОБРАНО" +
" | " + key->getFullPrice() * products[key] + "\n";
}
info->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10.00F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
info->AutoSize = true;
info->Location = System::Drawing::Point(10, y);
info->Name = L"label4";
info->Size = System::Drawing::Size(100, 25);
info->TabIndex = 2;
info->Text = product_by_score;
productLabels.Add(key,info );
y += 30;
}
}
//реализация сравнения в классе Product_for_sale
int Product_for_sale::equals(Product_for_sale^ pfs) {
if (this->name->Equals(pfs->getName())) {
return 0;
}
else return 1;
}
int Product_for_sale::CompareTo(Object^ obj){
if (obj->GetType() == Product_for_sale::typeid) {
Product_for_sale^ product = dynamic_cast<Product_for_sale^>(obj);
return equals(product);
}
else return 1;
// throw gcnew ArgumentException("object is not a Score");
}
错误正好在表达式products[key]上崩溃,而key本身,您可以从对象中工作和获取数据。
我在入口处检查了列表的占用情况,一切都是正确的,无论是键还是值。同样,如果列表中有2对,一切都没有问题。
1条答案
按热度按时间gjmwrych1#
在提供的equals方法中,如果名称相等,则返回0,如果不相等,则返回1。这不符合标准惯例。将整个代码段替换如下: