我有一个存储多个对象类型的集合,一个Textbox和一个Textblock,我这样声明:
List<object> textBoxCollection= new List<object>();
但是,当我运行一个仅查找Textbox对象的foreach循环时,它会抛出一个invalidcastexception。我对foreach循环的假设是它只会对我调出的对象类型运行操作。我哪里错了?继承我的循环:
foreach (MyTextBox mtb in textBoxCollection)
{
int number
bool mybool = Int32.TryParse(mtb.Text, out number);
if (mybool == false)
{
//some operation
}
else
{
//some other operation
}
}
答案 0 :(得分:11)
您需要使用OfType<T>()
foreach (MyTextBox mtb in textBoxCollection.OfType<MyTextBox>())
{ ... }
答案 1 :(得分:1)
您可以使用is
语句检查对象类型:
foreach (object tmp in textBoxCollection)
{
if(tmp is MyTextBox) {
MyTextBox mtb = (MyTextBox )tmp;
int number
bool mybool = Int32.TryParse(mtb.Text, out number);
if (mybool == false)
{
//some operation
}
else
{
//some other operation
}
}
}
或类似陈述as
:
foreach (object tmp in textBoxCollection)
{
MyTextBox mtb = tmp as MyTextBox;
if(mtb != null) {
.......
}
}