简体   繁体   English

无法比较数组中的两个元素

[英]Failed to compare two elements in the array

private SortedList<ToolStripMenuItem, Form> forms = new SortedList<ToolStripMenuItem, Form>();                

private void MainForm_Load(object sender, EventArgs e)
{
   formsAdd(menuCommandPrompt, new CommandPrompt());
   formsAdd(menuLogScreen, new LogScreen()); //Error
}

private void formsAdd(ToolStripMenuItem item, Form form)
{
   forms.Add(item, form); //Failed to compare two elements in the array.
   form.Tag = this;
   form.Owner = this;
}

I can't get that why it throws error. 我无法理解为什么它会抛出错误。 Error occurs on second line of form load event. 第二行表单加载事件发生错误。

formsAdd method simply adds form and toolstip element to the array(forms) and sets tag and owner of form to this. formsAdd方法只是将form和toolstip元素添加到数组(表单)并将表单的标记和所有者设置为此。 On second call of function, it throws an error. 在第二次调用函数时,它会抛出一个错误。

CommandPrompt, LogScreen /* are */ Form //s
menuCommandPrompt, menuLogScreen /* are */ ToolStripMenuItem //s

错误

You have a SortedList , but ToolStripMenuItem does not implement IComparable , so the list does not know how to sort them. 您有一个SortedList ,但ToolStripMenuItem没有实现IComparable ,因此列表不知道如何对它们进行排序。

If you don't need to have the items sorted, you can use a list of Tuple s or a Dictionary , depending on what exactly do you want to do. 如果您不需要对项目进行排序,则可以使用TupleDictionary的列表,具体取决于您想要做什么。

If you want to have them sorted, you need use the overload of SortedLists 's constructor that takes IComparer . 如果要对它们进行排序,则需要使用带有IComparerSortedLists构造函数的重载 That means you have to implement that interface in some way. 这意味着您必须以某种方式实现该接口。

Do both your object types implement IComparable? 你的对象类型都实现了IComparable吗? This is a must for the sorted list to compare the objects it is adding to the array. 这是排序列表必须比较它添加到数组的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM