C# 2.0 泛型:如何创建零参数的 Action 对象
首先,我使用的是 VS2005 和 C# 2.0。
我正在尝试从 SelectedIndexChanged 事件内部设置组合框的 Text 属性。 来自另一个线程 在 StackOverflow 上,建议按以下方式完成:
BeginInvoke(new Action(() => someCombobox.Text = "x" ));
现在,首先这会为我返回一个编译器错误。 我相信这是因为 Action 对象在两种语言规范中的行为不同。 在 C# 2.0 中,Action 对象似乎在所有声明中都需要
结构。 也许我错了,但我想澄清这一点。
有效的方法如下:
BeginInvoke(new Action<string>( delegate { someCombobox.Text = "x"; }), new object[] { "" });
但是,对我来说,我必须使用类型参数定义 Action 对象(特别是因为我不打算传递任何参数),这对我来说似乎很奇怪! 不知何故,删除此参数也会使空的 new object[] 过时,这正是我想要的。
谁能帮我简化上面的调用?
最后,是否保证 BeginInvoke 将在 SelectedIndexChanged 之后完成,从而使用正确的文本更新组合框的 Text 属性?
我真的很高兴知道这些问题的答案。
First of all, I'm using VS2005 and C# 2.0.
I'm trying to set a combobox' Text property from inside the SelectedIndexChanged event. From another thread here on StackOverflow this was proposed done the following way:
BeginInvoke(new Action(() => someCombobox.Text = "x" ));
Now, first of all this returns a compiler error for me. I believe that is because the Action object behaves differently in the two language specifications. In C# 2.0, the Action object seems to need the <T>
structure in all declarations. Maybe I'm wrong, but I'd like to have that clarified.
What does work is the following:
BeginInvoke(new Action<string>( delegate { someCombobox.Text = "x"; }), new object[] { "" });
However, it just seems very weird to me that I have to define the Action object with a type parameter (especially since I'm not intending to pass any parameters)! Somehow removing this parameter would also make the empty new object[] obsolete, which is what I want.
Can anyone help me simplify the above call?
Finally, is it guaranteed that BeginInvoke will finish after the SelectedIndexChanged and thus update the combobox' Text property with the correct text?
I'd really appreciate to learn the answers to these questions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以定义自己的操作委托。
delegate void Action()
我看不到您调用 BeginInvoke 的对象,但如果它是与组合框在同一线程上创建的 UI 控件,则保证您传递的委托在 SelectedIndexChanged 事件处理程序完成后一段时间调用。
You could define your own Action delegate.
delegate void Action()
I can't see the object on which you're calling BeginInvoke, but if it is a UI control created on the same thread as the combobox, the delegate you pass is guaranteed to be invoked some time after the SelectedIndexChanged event handler completes.
我认为 .NET 2.0 中不提供不带参数的操作
不用担心 - 只需使用不同的预定义委托类型即可。
MethodInvoker 应该完成这项工作(不带参数的 void 方法)。
此外,BeginInvoke 有 2 个重载 - 一种重载采用委托,另一种重载采用委托和对象数组。
I don't think Action without parameters is available in .NET 2.0
No worries - just use a different predefined delegate type.
MethodInvoker should do the job (void method with no parameters).
Also, BeginInvoke has 2 overloads - one that takes a delegate, and one that takes a delegate and array of objects.