如何使用函数更改表单属性中的对象?

时间:2013-01-16 22:35:47

标签: c#

假设您正在尝试设置标签的文字。通过这样做,您可以调用函数SetText(labelname,“texthere”)。 SetText'标题'会是什么?

我正在尝试:

private void SetText(object foo, string bar) 

但这不起作用

编辑:我有这个:

private void SetText(Control thing, string text)
{
if (this.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
Invoke(d, new object[] { text });
}
else
{
thing.Text = text;
}
}

但它说的是一些无效的参数数量。我需要改变什么?

2 个答案:

答案 0 :(得分:1)

使用Control class代替Object,因为前者定义了控件的基类(具有可视化表示的组件)并公开了Text属性。

private void SetText(Control control, String text)
{
    control.Text = text;
}

像这样,您不需要装箱/投射对象。否则,您还应该指定对象的类型,因为您可以传递TextBox,Label等......

答案 1 :(得分:0)

<可能是因为您引用了错误的对象,请尝试:

private void SetText(ref object foo, string bar)

请注意ref关键字。