How do I create a template function for controls o

2020-04-17 06:21发布

This statement will change the position of a form object.

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

I would like to write a generic template function that can position any form object.

I came up with this, but it is invalid:

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

and I call it like this:

    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?)

Do I need to mention some kind of interface on the template function? How do I call an extension method on a generic type?

2条回答
够拽才男人
2楼-- · 2020-04-17 06:43

You don't need a generic method, you can do it this way:

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

The base class for all controls of your form is Control which has Location property.

查看更多
太酷不给撩
3楼-- · 2020-04-17 06:55

What you can do is add where T : Control onto the definition of the function. Control is the highest point in the hierarchy that defines the Point Location.

public void ChangePosition<T>(T form_object) where T : Control
{
    form_object.Location = new Point(0,0);
}
查看更多
登录 后发表回答