How to find out if an object is a <type> or decendant <type>

I have the following code:

foreach (var control in this.Controls)
{

}

I want to do something like control.Hide(). But the items in the collection are this.Controlsnot of type Control(they are Object).

I don't seem to remember how to safely use this to call hide if it really has a type Controland does nothing. (I am a transplanted delphi programmer, and I keep thinking about something like that control is Control.)

+3
source share
6 answers

Here is the case when you do not want to use var.

foreach (Control control in this.Controls)
{
    control.Hide();
}

does exactly what you want.

Check it out if you don't believe it.

In other scenarios where there might potentially be a mixed collection, you can do something like

foreach (var foo in listOfObjects.OfType<Foo>())
{

}
+5

.

foreach (var control in this.Controls)
{
    if(control is Control) 
    {
        ((Control)control).Hide(); 
    }
}
+1
Control c = control as Control;
if (c != null)
    c.Hide();

if (control is Control)
    ((Control)control).Hide();
+1

foreach(var control in this.Controls.OfType<Control>())
{
  control.Hide();
}
+1

( ), , .

I came across a situation where it Type.IsAssignableFromcorresponds to what I need, when isI did not. (Unfortunately, I don’t remember what the situation was.)

+1
source

There are several ways to do this:

if (control is Control)
    ((Control)control).Hide();

or

if (control is Control)
    (control as Control).Hide();

or if you just want to iterate over the controls,

foreach(var control in this.Controls.Cast<Control>())
    control.Hide();
0
source

Source: https://habr.com/ru/post/1741383/


All Articles