c# - 从 control.Invoke((MethodInvoker) delegate {/* ... */} 返回值;我需要一些解释

标签 c# invoke

#1 和#2 有什么区别:

代码 1(编译成功):

        byte[] GetSomeBytes()
  {
            return (byte[])this.Invoke((MethodInvoker)delegate 
            { 
                GetBytes(); 
            });
  }

  byte[] GetBytes()
  {
   GetBytesForm gbf = new GetBytesForm();

   if(gbf.ShowDialog() == DialogResult.OK)
   {
    return gbf.Bytes;
   }
   else
    return null;
  }

代码 2(不符合 ok)

int GetCount()
{
       return (int)this.Invoke((MethodInvoker)delegate
       {
           return 3;            
       });
}

代码 #2 告诉我由于“System.Windows.Forms.MethodInvoker”返回 void,return 关键字后面不能跟对象表达式

我该如何解决?为什么(做)编译器认为代码 #1 是正确的?

最佳答案

要回答您的第一个问题,请尝试像这样更改您的第一个样本:

return (byte[])this.Invoke((MethodInvoker)delegate 
{ 
    return GetBytes(); 
});

此时,您将遇到相同的编译错误。

public object Invoke(Delegate method)返回一个对象,所以你可以将返回值转换为任何东西,它会编译。但是,您正在传递类型为 MethodInvoker 的委托(delegate)。 , 它有一个签名 delegate void MethodInvoker() .因此,在您转换为 MethodInvoker 的方法体内,您不能 return任何东西。

第二个试试这个:

return (int)this.Invoke((Func<int>)delegate
{
    return 3;
});

Func<int>是一个返回 int 的委托(delegate),所以它会编译。

关于c# - 从 control.Invoke((MethodInvoker) delegate {/* ... */} 返回值;我需要一些解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3117957/

相关文章:

c# - 将 Invoke 与扩展应用程序上下文的 UI 元素一起使用?

C# 非常快速地从文本文件添加数千行到数据库

c# - 在 C# 中使用 sqlite 进行 SQL 转义

C# .NET 生成一次字符串数组,其索引是表中的字符串值

c# - 带输出参数的 control.invoke

c++ - 为什么 `std::invoke` 不是 constexpr?

c# - 调用异步订单

c# - 任何用于 RED5 媒体服务器的 .NET API 或任何其他具有 .NET API 的跨平台媒体服务器?

c# - 使用完 .NET 服务引用客户端后是否需要关闭它

java - 错误: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference