#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;
}
代码 2(不符合 ok)
int GetCount()
{
return (int)this.Invoke((MethodInvoker)delegate
{
return 3;
});
}
代码 #2 告诉我由于“System.Windows.Forms.MethodInvoker”返回 void,return 关键字后面不能跟对象表达式。
我该如何解决?为什么(做)编译器认为代码 #1 是正确的?
最佳答案
要回答您的第一个问题,请尝试像这样更改您的第一个样本:
return (byte[])this.Invoke((MethodInvoker)delegate
{
return GetBytes();
});
此时,您将遇到相同的编译错误。
public object Invoke(Delegate method)
返回一个对象,所以你可以将返回值转换为任何东西,它会编译。但是,您正在传递类型为 MethodInvoker
的委托(delegate)。 , 它有一个签名 delegate void MethodInvoker()
.因此,在您转换为 MethodInvoker 的方法体内,您不能 return
任何东西。
第二个试试这个:
return (int)this.Invoke((Func<int>)delegate
{
return 3;
});
Func<int>
是一个返回 int 的委托(delegate),所以它会编译。
关于c# - 从 control.Invoke((MethodInvoker) delegate {/* ... */} 返回值;我需要一些解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3117957/