control.invoke 带有输出参数

control.invoke with an out parameter

Winforms、C#、VS2010。

我有一个 运行 在我的应用程序生命周期内的轮询线程。

有时它会在我的主窗体上调用一个事件。我已经很多年没有碰过代码了,它是 运行 成功的,但现在我需要在参数列表中添加一个 "out" 参数。我在网上搜索过,但我发现的所有线程都与反射有关,并且尝试转换为我的上下文很复杂。我的不使用反射。

有人可以帮忙解决这个问题吗?在我读到的反射线程上,人们似乎会检查一些对象数组以获得输出参数结果,我没有在我的代码中使用它,而且我也不知道从哪里得到它。

private bool OnNeedUpdateCreateEvent(string title, string message,
  bool creatingNew, out string newPlanName)
{
    newPlanName = "";

    // 1st pass through this function. 
    // Check to see if this is being called from another thread rather 
    // than the main thread. If so then invoke is required
    if (InvokeRequired)
    {
      // Invoke and recall this method.
      return (bool)Invoke(new onNeedToUpdatePlanEvent(OnNeedUpdateCreateEvent),
        title, message, creatingNew, out newPlanName); <- wrong out param

    }
    else
    {
      // 2nd pass through this function due to invoke, or invoke not required
      return InputDlg(this, title, message, creatingNew, out newPlanName);
    }

} 

很像你已经知道了,只是你还没有找到数组。它由编译器自动创建。 Invoke method 的签名是:

public object Invoke(
    Delegate method,
    params object[] args
)

params关键字让编译器auto-create数组。不错的语法糖,但在这里对您没有帮助。你只需要自己做,就像这样:

if (!creatingNew) {
    // Invoke and recall this method.
    object[] args = new object[] { title, message, creatingNew, null };
    var retval = (bool)Invoke(new onNeedToUpdatePlanEvent(OnNeedUpdateCreateEvent), args);
    newPlanName = (string)args[3];
    return retval;
}
// etc..