简体   繁体   English

C#2.0泛型:如何使用零参数创建Action对象

[英]C# 2.0 generics: How to create an Action object with zero parameters

First of all, I'm using VS2005 and C# 2.0. 首先,我正在使用VS2005和C#2.0。

I'm trying to set a combobox' Text property from inside the SelectedIndexChanged event. 我正在尝试从SelectedIndexChanged事件内部设置组合框的Text属性。 From another thread here on StackOverflow this was proposed done the following way: 在StackOverflow上的另一个线程中 ,提出了以下方法:

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. 我认为这是因为Action对象在两种语言规范中的行为有所不同。 In C# 2.0, the Action object seems to need the <T> structure in all declarations. 在C#2.0中,Action对象似乎在所有声明中都需要<T>结构。 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)! 但是,对我来说似乎很奇怪,我必须使用类型参数定义Action对象(尤其是因为我不打算传递任何参数)! Somehow removing this parameter would also make the empty new object[] obsolete, which is what I want. 以某种方式删除此参数还会使空的new object []过时,这正是我想要的。

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? 最后,是否可以确保BeginInvoke将在SelectedIndexChanged之后完成,从而用正确的文本更新组合框的Text属性?

I'd really appreciate to learn the answers to these questions. 我非常感谢您学习这些问题的答案。

I don't think Action without parameters is available in .NET 2.0 No worries - just use a different predefined delegate type. 我认为.NET 2.0中不提供没有参数的操作。不用担心-只需使用其他预定义的委托类型。 MethodInvoker should do the job (void method with no parameters). MethodInvoker应该执行此工作(无参数的空方法)。

Also, BeginInvoke has 2 overloads - one that takes a delegate, and one that takes a delegate and array of objects. 另外,BeginInvoke有2个重载-一个重载接受委托,一个重载接受委托和对象数组。

BeginInvoke(new MethodInvoker(delegate()
{
    someCombobox.Text = "x";
}));

You could define your own Action delegate. 您可以定义自己的Action委托。

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. 我看不到要在其上调用BeginInvoke的对象,但是如果它是在与组合框相同的线程上创建的UI控件,则可以确保在SelectedIndexChanged事件处理程序完成后的某个时间调用您传递的委托。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM