c# – 从control.Invoke返回值((MethodInvoker)委托{/ * … * /}
发布时间:2020-12-15 20:05:13 所属栏目:百科 来源:网络整理
导读:#1和#2之间有什么区别: 代码1(编译好): byte[] GetSomeBytes() { return (byte[])this.Invoke((MethodInvoker)delegate { GetBytes(); }); } byte[] GetBytes() { GetBytesForm gbf = new GetBytesForm(); if(gbf.ShowDialog() == DialogResult.OK) { retu
#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,返回关键字后面不能跟一个对象表达式. 我该如何解决?为什么(做)编译器认为代码#1是对的? 解决方法
要回答您的第一个问题,请尝试更改您的第一个示例,如下所示:
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的委托,因此它将被编译. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |