Return value from control.Invoke ((MethodInvoker) delegate {/ * ... * /}; I need explanations

What is 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 (not respected normally)

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

Code # 2 gives me. Since "System.Windows.Forms.MethodInvoker" returns void, the return keyword should not be accompanied by an object expression.

How can i fix this? And why (do) complier think code number 1 is right?

+3
source share
2 answers

To answer your first question, try changing your first example as follows:

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

At this point, you will have the same compilation error.

public object Invoke(Delegate method) , . MethodInvoker, delegate void MethodInvoker(). , , Invoker, return -.

:

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

Func<int> , int, .

+22

Code # 1 - GetBytes(), . , ( void).

# 2 , , ( "3" ) void.

+1
source

Source: https://habr.com/ru/post/1751747/


All Articles