如何为表单控件创建模板函数?

How do I create a template function for controls of a form?

此语句将更改表单对象的位置。

lblMessage.Location = new Point(0,0);

我想编写一个通用模板函数,它可以定位任何表单对象。

我想到了这个,但它无效:

public void ChangePosition<T>(T form_object)
{
    form_object.Location = new Point(0,0);
}

我这样称呼它:

    ChangePosition(lblMessage);

Error: 'T' does not contain a definition for 'Location' and no extension method 'Location' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

我需要在模板函数上提及某种接口吗?如何调用泛型类型的扩展方法?

您可以做的是将 where T : Control 添加到函数的定义中。 Control 是定义 Point Location.

的层次结构中的最高点
public void ChangePosition<T>(T form_object) where T : Control
{
    form_object.Location = new Point(0,0);
}

你不需要泛型方法,你可以这样做:

public void ChangePosition(Control form_object)
{
    form_object.Location = new Point(0,0);
}

表单所有控件的基础 class 是 Control,它有 Location 属性。