开发者

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

开发者 https://www.devze.com 2022-12-27 15:34 出处:网络
I have the following code: foreach (var control in this.Con开发者_运维百科trols) { } I want to do something like control.Hide() in there.But the items in the this.Controls collection are not of ty

I have the following code:

foreach (var control in this.Con开发者_运维百科trols)
{

}

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

I can't seem to remember the safe way to cast this to call hide if it is really of type Control and do nothing otherwise. (I am a transplanted delphi programmer and I keep thinking something like control is Control.)


Here's a case where you don't want to use var.

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

does exactly what you want.

Test it if you do not believe.

For other scenarios where you could potentially have a mixed collection, you could do something like

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

}


That's exactly it.

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


All the other answers (confirming your hunch) are probably right.

I have encountered a situation where Type.IsAssignableFrom matched what I needed when is didn't. (Unfortunately, I don't remember now what the situation was.)


Or as an Alternative you could also do

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


Control c = control as Control;
if (c != null)
    c.Hide();

or

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


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

精彩评论

暂无评论...
验证码 换一张
取 消