#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(没有遵守)
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 void MethodInvoker()
。因此,在转换为 MethodInvoker 的方法体内,您不能return
任何事物。
对于第二个,请尝试此操作:
return (int)this.Invoke((Func<int>)delegate
{
return 3;
});
Func<int>
是一个返回 int 的委托,因此它将编译。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)