有一个变量,声明如下:Control ctl;现在我要判断它为哪个控件,用如下判断语句:if (ctl == control1 || ctl == control2 || ctl == control3 || ctl ==      
control4 .......)这样判断非常麻烦,能不能把  control1、control2、control3、control4....作为一个集合,然后再拿ctl从这个集合里做查找来进行判断?
如何判断?谢谢个位大大。

解决方案 »

  1.   

    Control A = new Control();
                Control B = new Control();
                Control C = new Control();
                Control D = new Control();
                List<Control> list = new List<Control>();
                list.Add(A);
                list.Add(B);
                list.Add(C);
                list.Add(D);
                Control D1 = D;
                Control E = new Control();
                MessageBox.Show(list.IndexOf(D1).ToString());//输出3,也就是大于0
                MessageBox.Show(list.IndexOf(E).ToString());//找不到,输出-1
      

  2.   

    Label lbName = new Label();
            Button btnAdd = new Button();        SortedList<Type, bool> cotrolTypeCollections= new SortedList<Type, bool>();
            cotrolTypeCollections[typeof(Label)] = true;
            cotrolTypeCollections[typeof(Button)]= true;        
            if (cotrolTypeCollections.ContainsKey(lbName.GetType())){ /*存在此控件*/ }
            if (cotrolTypeCollections.ContainsKey(btnAdd.GetType()){ /*存在此控件*/ }
      

  3.   

    SortedList<Type, bool> cotrolTypeCollections= new SortedList<Type, bool>();//用来装你需要的控件类型集合
            cotrolTypeCollections.Add(typeof(Label),true);//向集合中添加Label控件类型
            cotrolTypeCollections.Add(typeof(Button),true);//向集合中添加Button控件类型
            cotrolTypeCollections.Add(typeof(TextBox),true);//向集合中添加TextBox控件类型
            Label lbName = new Label();
            Button btnAdd = new Button();
            
            if (cotrolTypeCollections.ContainsKey(lbName.GetType())){ /*存在此控件*/ }
            if (cotrolTypeCollections.ContainsKey(btnAdd.GetType())){ /*存在此控件*/ }