C#的Compiler Error CS1660

本文解决了一个C#编程中使用Invoke与Delegate时遇到的CompilerErrorCS1660的问题,提供了正确的代码实现方式。通过分析错误原因,解释了为什么直接使用匿名委托会导致错误,并给出了修改后的正确代码片段。此教程适用于希望理解并正确使用C#中的Invoke和Delegate的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:http://stackoverflow.com/questions/3926500/base-invoke-with-delegates

问题:

I am invoking a delegate and I'm not very informed about how it works and I have compilation errors because of it (Compiler Error CS1660). This is the code I have for it:

base.Invoke( delegate { bool flag = (((this.layerPickPlaceProcess != null) && (this.robotComponent != null)) && ((((StateEnum) this.layerPickPlaceProcess.State) == StateEnum.Idle) || (((StateEnum) this.layerPickPlaceProcess.State) == StateEnum.Ready))) && ((((StateEnum) this.robotComponent.State) == StateEnum.Idle) || (((StateEnum) this.robotComponent.State) == StateEnum.Ready)); this.cmdManualPlace.Enabled = flag; });


原因:

this is because Invoke accepts Delegate which is not (sic!) a delegate type as far as the C# compiler is concerned. A delegate type should define a call signature, while Delegate does not and is just a common ancestor. The expression delegate { ... } has type... try to guess... anonymous delegate(if it was a method it would be method group). They are not delegate types either! But they can be implicitly converted to a delegate type that has a matching signature. And delegate types can be implicitly converted to Delegate.

Action is: public delegate void Action();

simply, chains:

  • Anonymous method → Delegate: no conversion exists
  • Anonymous method → Action: implicit conversion if signature matches
  • Action → Delegate: implicit conversion (Action is descendant of Delegate)

Combine them:

  • Anonymous method → Action → Delegate: it works!
尝试以下代码即可解决:


// MethodInvoker is also acceptable. Action action = delegate { bool flag = (((this.layerPickPlaceProcess != null) && (this.robotComponent != null)) && ((((StateEnum) this.layerPickPlaceProcess.State) == StateEnum.Idle) || (((StateEnum) this.layerPickPlaceProcess.State) == StateEnum.Ready))) && ((((StateEnum) this.robotComponent.State) == StateEnum.Idle) || (((StateEnum) this.robotComponent.State) == StateEnum.Ready)); this.cmdManualPlace.Enabled = flag; }; base.Invoke(action);


转载于:https://www.cnblogs.com/hold/archive/2011/09/22/2286778.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值