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

Vaj*_*ura 0 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);
}
Run Code Online (Sandbox Code Playgroud)

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

Sri*_*vel 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;
}
Run Code Online (Sandbox Code Playgroud)

然后用它作为

main()
{
    TextBox t = CreateInstance<TextBox>(1,1,100,100);
}
Run Code Online (Sandbox Code Playgroud)

另外,我将通过传递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;
}
Run Code Online (Sandbox Code Playgroud)

然后用它作为

main()
{
    TextBox t = CreateInstance<TextBox>(new Rectangle(1,1,100,100));
}
Run Code Online (Sandbox Code Playgroud)