简体   繁体   中英

How to get objects of specific type from a List of objects

I have a collection which stores multiple object types, a Textbox and a Textblock, which i am declaring like this:

List<object> textBoxCollection= new List<object>();

However, when i run a foreach loop looking just for the Textbox object, it throws an invalidcastexception. My assuption of the foreach loop is that it would only run the operation on the object type i have called out. Where am i going wrong? Heres my loop:

foreach (MyTextBox mtb in textBoxCollection)
{

    int number
    bool mybool = Int32.TryParse(mtb.Text, out number);

    if (mybool == false)
    {
        //some operation
    }
    else
    {
        //some other operation
    }
} 

You need to narrow down the enumeration to only the correct type using OfType<T>()

foreach (MyTextBox mtb in textBoxCollection.OfType<MyTextBox>())
{ ... }

You can check object type using is statement:

    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
           }
        }
     } 

Or similar statement as :

    foreach (object tmp in textBoxCollection)
    {
        MyTextBox mtb = tmp as MyTextBox;
        if(mtb != null) {
        .......
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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