How to create a template function for form controls?

This operator will change the position of the 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 not valid:

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 there is no extension method "Location" that takes the first argument of type "T" (if you did not specify a directive or assembly link?)

Do I need to mention some kind of interface for the template function? How to call extension method for generic type?

+2
source share
2

, where T : Control . Control - , Point Location.

public void ChangePosition<T>(T form_object) where T : Control
{
    form_object.Location = new Point(0,0);
}
+1

, :

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

- Control, Location.

+3

Source: https://habr.com/ru/post/1672932/


All Articles