如何在C#中添加控件功能?

时间:2014-08-11 08:37:40

标签: c# function controls

如何使一个函数有一个参数接收控件的类型(如Button,GroupBox,Panel,TextBox,Label ...等)

private void CreateControl()
{
   Button myButton=new Button();
   this.Controls.Add(myButton);
}

我需要设置一个参数来控制控件的类型并不总是按钮。

请帮忙

3 个答案:

答案 0 :(得分:6)

如果您想传递类型,可以通过 generic 来完成:

// Probably, you'd rather return T (created control), not void 
public void CreateControl<T>() 
  where T: Control, new() {

  this.Controls.Add(new T());
}

...

CreateControl<Button>();

答案 1 :(得分:0)

如果您不想使用Reflection复杂化,可以创建enum并将其作为参数发送:

public enum ControlType
{
    Button,
    Label,
    TextBox,
    //....
}

然后,您的方法调用将是

private void CreateControl(ControlType control)
{
    switch(control)
    {
        case Button : 
            Button myButton=new Button();
            this.Controls.Add(myButton);
            break;
       //case etc
    }        
}

答案 2 :(得分:-1)

Control类是所有Winforms控件的基类。您可以将参数设置为基本类型,但它也将接受更多派生类型。

尝试:

public void CreateControl(Control control)
{
    this.Controls.Add(control);
}
相关问题