return value from control.Invoke((MethodInvoker) d

2019-04-12 12:39发布

What's the difference between #1 and #2:

Code 1 (compiled ok):

        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;
  }

Code 2 (didn't complied ok)

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

Code #2 gives me Since 'System.Windows.Forms.MethodInvoker' returns void, a return keyword must not be followed by an object expression.

How can I fix it? And why (do) complier think code #1 is right?

标签: c# invoke
2条回答
别忘想泡老子
2楼-- · 2019-04-12 13:03

In Code #1, your delegate does not return a value - it simply executes GetBytes(), but doesn't return anything. The compiler will not complain because it is not expecting a return value (this is a void method).

However, in code #2 you try to return a value from the delegate -- which is compiler complains about, because you cannot return a value (in this case '3') from a void method.

查看更多
Anthone
3楼-- · 2019-04-12 13:10

To answer your first question, try altering your first sample like this:

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

At this point, you'll have the same compilation error.

public object Invoke(Delegate method) returns an object, so you can cast the return value to anything and it will compile. However, you are passing in a delegate of type MethodInvoker, which has a signature delegate void MethodInvoker(). So, within the body of the method that you cast to MethodInvoker, you cannot return anything.

Try this instead for the second one:

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

Func<int> is a delegate that returns an int, so it will compile.

查看更多
登录 后发表回答