问题
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?
回答1:
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);
}
回答2:
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.
来源:https://stackoverflow.com/questions/35945723/how-do-i-create-a-template-function-for-controls-of-a-form