#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 (byte[])this.Invoke((MethodInvoker)delegate { return GetBytes(); });
此时,您将遇到相同的编译错误.
公共对象Invoke(Delegate方法)返回一个对象,因此您可以将返回值强制转换为任何对象并进行编译.但是,您传入一个MethodInvoker类型的委托,它具有签名委托void MethodInvoker().因此,在您转换为MethodInvoker的方法体内,您无法返回任何内容.
试试这个而不是第二个:
return (int)this.Invoke((Func<int>)delegate { return 3; });
FUNC< INT>是一个返回int的委托,因此它将被编译.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。