Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

winforms - C# 2.0 generics: How to create an Action object with zero parameters

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...