C#在List <type>中查找typeof(type)

时间:2018-01-31 02:08:48

标签: c# collections typeof

简化代码。

ObservableCollection<UserControl> controls = new ObservableCollection<UserControl>();

void main(){
  controls.Add(new Navigation) //Navigation is of type UserControl
  ... //controls.Add(new UserControl) for each UserControl
}
private void ToggleNavigation(){
  for(int i = 0; i < controls.Count; i++){
    if(controls.GetType() == typeof(Navigation)){
      controls[i].Visible = controls[i].Visible ? false : true;
    }
  }
}

我想知道在List中找到某个日期类型是否有简化。 所以,我想有这样的事情:

int index = controls.IndexOf(typeof(Navigation)); //<--I am looking for a Valid Statement

controls[index].Visible = controls[index].Visible ? false : true;

2 个答案:

答案 0 :(得分:1)

尝试使用以下内容:

var control = controls.FirstOrDefault(s => s.GetType() == typeof(Navigation)) as Navigation;
if (control != null) 
{
    control.Visible = !control.Visible;
}

答案 1 :(得分:0)

您可以简化为:

private void ToggleNavigation() 
{
   for(int i = 0; i < controls.Count; i++)
   {
     var control = controls[i];
     if (control is Navigation)
     {
        control.Visible = !control.Visible;
     }
   }
}

如果你想要切换可见性的多个X型控件,这将有效。