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 个元素时才会发出错误。同时,如果1号有3个错误,如果1号有5个错误,那么1号和3号又会有4个。
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] 上与密钥本身崩溃,您可以工作并从对象获取数据。
我检查了入口处的占用列表,一切都正确,无论是键还是值。再说一次,如果列表中有 2 对,则一切正常。
这个决定是正确的,谢谢
`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 name->CompareTo(product->getName());
}
else return 1;
}`