用于将类类型作为参数传递的C#语法?

时间:2014-08-22 06:33:55

标签: c#

我想在某种意义上概括了控件的创建以便于使用。

public static Control mkC(TYPE type, int x, int y, int w, int h)
{
    Control c;
    c = new type();
    c.Location = new Point(x, y);
    c.Size = new Size(w, h);
    return (type)c;
}

main()
{
    TextBox t = mkC(TextBox, 1,1,100,100);
}

但我不知道做我想做的确切方式。

2 个答案:

答案 0 :(得分:10)

使用泛型

public static T CreateInstance<T>(int x, int y, int w, int h) where T : Control, new()
{
    T c = new T();
    c.Location = new Point(x, y);
    c.Size = new Size(w, h);
    return c;
}

然后将其用作

main()
{
    TextBox t = CreateInstance<TextBox>(1,1,100,100);
}

此外,我将通过传递Rectangle结构来减少参数数量。

public static T CreateInstance<T>(Rectangle rect) where T : Control, new()
{
    T c = new T();
    c.Location = rect.Location;
    c.Size = rect.Size;
    return c;
}

然后将其用作

main()
{
    TextBox t = CreateInstance<TextBox>(new Rectangle(1,1,100,100));
}

答案 1 :(得分:0)

这里提到两个选项:

下面的选项与您提到的同一行。您需要将类型作为参数传递,然后使用类型的CreateInstance()方法。还必须将实例强制转换为特定控件。         public Control CreateControlInstance(Type type,int x,int y,int w,int h)         {             Control c =(Control)Activator.CreateInstance(type);             c.Location = new Point(x,y);             c.Size = new Size(w,h);             返回c;         }

    private main()
    {
        TextBox t = (TextBox) CreateControlInstance(typeof (TextBox), 1, 1, 100, 100);
    }

您也可以编写如下所述的通用函数:

    public static T CreateControlInstance<T>(int x, int y, int w, int h) where T : Control, new()
    {
        T c = new T();
        c.Location = new Point(x, y);
        c.Size = new Size(w, h);
        return c;
    }

    private main()
    {
        TextBox t = CreateControlInstance<TextBox>(1, 1, 100, 100);
    }