【问题标题】:How to get return value of function called from a Invoke method如何获取从 Invoke 方法调用的函数的返回值
【发布时间】:2011-11-03 18:29:41
【问题描述】:

我需要解释..为什么下面的代码给出:Parameter count mismatch

C#代码:

//... 
public delegate int FindInRichTextBoxMethod(RichTextBox rtx, string target, int index);
 public int FindInRichTextBox(RichTextBox rtx, string target, int index)
    {
        return rtx.Find(target, index, RichTextBoxFinds.None);
    }
// ... 
int start; 
string tempState = "foo";

if (lista.InvokeRequired) {
  object find = Invoke((FindInRichTextBoxMethod)delegate
                            {
                                return FindInRichTextBox(list, tempState, len);
                            });  

                            start = (int)find;
} else {

      start = FindInRichTextBox(list, tempState, len);
 }

提前致谢。

【问题讨论】:

    标签: c# .net winforms multithreading invoke


    【解决方案1】:

    Invoke() 的参数包括一个委托,以及传递给该委托的参数。您正在尝试传递 FindInRichTextBoxMethod 委托,但该委托类型需要三个参数。您需要:

    1. 使用您的FindInRichTextBox 方法构造一个委托,然后
    2. 将参数传递给该委托。

    类似这样的:

    var finder = new FindInRichTextBoxMethod(FindInRichTextBox);
    object find = Invoke(finder, new object[] { list, tempState, len }); 
    

    另一种方法是传入闭包,有点像您在示例中尝试的那样。在您的情况下,错误是由于强制转换为FindInRichTextBoxMethod,因此 Invoke 需要参数。相反,您可以忽略演员表并像这样传递匿名委托:

    var find = Invoke(delegate { return FindInRichTextBox(list, tempState, len); });
    

    但是这行不通,因为编译器无法准确确定您想对该匿名委托做什么。同样,lambda 也不能自动转换:

    var find = Invoke(() => FindInRichTextBox(list, tempState, len));
    

    要了解问题的原因和解决方法,请阅读Why must a lambda expression be cast when supplied as a plain Delegate parameter

    【讨论】:

      【解决方案2】:

      您是否在Invoke 通话中收到此信息?我通常传递 Invoke 一个委托,然后传递一个包含要传递的变量的对象数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-28
        • 2016-03-27
        • 2015-12-03
        • 1970-01-01
        • 2011-11-13
        • 1970-01-01
        • 2015-08-25
        • 1970-01-01
        相关资源
        最近更新 更多