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

我只是一个虾纸丫 提交于 2019-12-02 04:33:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!