如何为表单控件创建模板函数? [英] How do I create a template function for controls of a form?

查看:152
本文介绍了如何为表单控件创建模板函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该声明将改变表单对象的位置。

This statement will change the position of a form object.

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

我想写一个泛型模板函数目的。

我想出了这个,但它是无效的:

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




错误:'T'不包含'位置'并且没有
的扩展方法'Location'接受类型'T'
的第一个参数可以被找到(你是否缺少using指令或汇编
引用?)

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?

推荐答案

您可以将添加到T:Control 函数的定义。 Control 是定义点位置的层级中的最高点。

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);
}

这篇关于如何为表单控件创建模板函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆