从control.Invoke((MethodInvoker)委托{/* ... */};返回值;我需要一些解释 [英] return value from control.Invoke((MethodInvoker) delegate { /* ... */ }; I need some explanations
问题描述
#1和#2有什么区别?
What's the difference between #1 and #2:
代码1(已编译,可以):
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;
}
代码2(未正确显示)
int GetCount()
{
return (int)this.Invoke((MethodInvoker)delegate
{
return 3;
});
}
代码#2给我由于'System.Windows.Forms.MethodInvoker'返回void,因此return关键字后不能包含对象表达式.
我该如何解决?为何编译器认为代码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.
public object Invoke(Delegate method)
返回一个对象,因此您可以将返回值强制转换为任何值,然后它将进行编译.但是,您传入的是类型为MethodInvoker
的委托,该委托具有签名delegate void MethodInvoker()
.因此,在转换为MethodInvoker的方法的主体内,您不能return
任何东西.
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屋!