[英]calling object members in c# foreach loop
I have lot of tab pages in my program and I want to add or remove these pages. 我的程序中有很多标签页,我想添加或删除这些页。 I'm using the following statement to do it. 我正在使用以下语句来做到这一点。
if(this.myControlForm.TabPages.Contains(tabPage1))
{
this.myControlForm.TabPages.Remove(tabPage1));
}
if(this.myControlForm.TabPages.Contains(tabPage2))
{
this.myControlForm.TabPages.Remove(tabPage2));
}
[...] //similar code for other tabPages
but it makes too much code when I have a lot of tabpages to add or remove so I want to add them in an array and make a foreach loop but I got an error 但是当我有很多标签页要添加或删除时,它的代码太多了,所以我想将它们添加到数组中并进行foreach循环,但是出现错误
my code is : 我的代码是:
object[] listToRemove = {tabPage1, tabPage2,tabPage3, ... tabPage20};
foreach ( object itr in listToRemove)
{
if(this.myControlForm.TabPages.Contains(itr))
{
this.myControlForm.TabPages.Remove(itr));
}
}
Why is this happening, can anyone please help? 为什么会这样,有人可以帮忙吗?
Change your listToRemove
to be explicitly typed, ie from array of objects to the array of TabPage
. 将listToRemove
更改为显式键入,即从对象数组更改为TabPage
数组。
Same story with itr
variable in loop. 循环中有itr
变量的同一个故事。
Contains
and Remove
methods expects argument to be of type TabPage
, not object
- that's why you're getting errors. Contains
和Remove
方法期望参数的类型为TabPage
,而不是object
-这就是为什么会出错的原因。
TabPage[] listToRemove = {tabPage1, tabPage2,tabPage3, ... tabPage20};
foreach (TabPage itr in listToRemove)
{
if(this.myControlForm.TabPages.Contains(itr))
this.myControlForm.TabPages.Remove(itr);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.