0

已经有一个关于这个的问题了。但这里有另一个问题有点不同,我找不到任何遮阳篷!

String text = this.GuiThread(() => this.comboBox1.Text); 

 if (text == "this")
 {
   //do somthing spectacular!
 }

text 是一个空变量左右..

使用未分配的局部变量。这是我得到的错误..并且 iv 测试了我可以在此处和 msdn 找到的所有示例。

我也有:

  public static class ControlExtensions
    {
        public static void GuiThread(this Control ctrl, Action action)
        {
            if (ctrl.InvokeRequired)
            {
                ctrl.BeginInvoke(action);
            }
            else
            {
                action.Invoke();
            }
        }
    }

想法?

4

1 回答 1

1

This code cannot compile. The GuiThread returns void, you are trying to assign that to a string. How you can get an exception is unguessable. It needs to at least look like this:

public static class ControlExtensions {
    public static T GuiThread<T>(this Control ctrl, Func<T> action) {
        if (ctrl.InvokeRequired) {
            return (T)ctrl.Invoke(action);
        }
        else {
            return action();
        }
    }
}

Don't write code like this, the actual ComboBox text you'll read is pretty random since it can be obtain while the user is modifying it. Give a thread the arguments it needs when you start it. The BackgroundWorker class keeps you out of trouble.

于 2012-04-24T23:21:12.387 回答