来自control.Invoke((MethodInvoker)委托的返回值{/*...*/};我需要一些解释

Але*_* Д. 3 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;
  }
Run Code Online (Sandbox Code Playgroud)

代码2(没有成功)

int GetCount()
{
       return (int)this.Invoke((MethodInvoker)delegate
       {
           return 3;            
       });
}
Run Code Online (Sandbox Code Playgroud)

代码#2给了我,因为'System.Windows.Forms.MethodInvoker'返回void,返回关键字后面不能跟一个对象表达式.

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

小智 24

要回答您的第一个问题,请尝试更改您的第一个示例,如下所示:

return (byte[])this.Invoke((MethodInvoker)delegate 
{ 
    return GetBytes(); 
});
Run Code Online (Sandbox Code Playgroud)

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

public object Invoke(Delegate method)返回一个对象,因此您可以将返回值强制转换为任何对象并进行编译.但是,您传入的是MethodInvoker具有签名的类型的委托delegate void MethodInvoker().因此,在您转换为MethodInvoker的方法体内,您无法做return任何事情.

试试这个而不是第二个:

return (int)this.Invoke((Func<int>)delegate
{
    return 3;
});
Run Code Online (Sandbox Code Playgroud)

Func<int> 是一个返回int的委托,因此它将被编译.