从control.Invoke((MethodInvoker)代表{/ * ... * /}返回值,我需要一些解释相关 [英] return value from control.Invoke((MethodInvoker) delegate { /* ... */ }; I need some explainations

查看:188
本文介绍了从control.Invoke((MethodInvoker)代表{/ * ... * /}返回值,我需要一些解释相关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么之间的#1和#2的区别:

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

代码1(编译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;
  }



2的代码(没有遵守OK)

Code 2 (didn't complied ok)

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



代码#2给我的由于'System.Windows.Forms的。 MethodInvoker返回void,返回关键字一定不能跟一个对象表达式

我怎样才能解决这个问题?和为什么(这么做)编者认为代码#1是正确的?

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

推荐答案

要回答你的第一个问题,尝试改变你的第一个样品一样这样的:

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.

公共对象调用(委托方法)返回一个对象,这样你就可以返回值转换到任何东西,它会编译。但是,您传递键入 MethodInvoker 的代表,其中有一个签名委托无效MethodInvoker()。所以,你投给MethodInvoker方法体中,你不能收益东西。

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.

试试这个对于第二个:

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



Func键< INT> 为代表的返回一个int,所以它会编译。

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

这篇关于从control.Invoke((MethodInvoker)代表{/ * ... * /}返回值,我需要一些解释相关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆