CS1503错误:无法将method group转换为System.Action<byte,byte,bool[*,*]>
解决Error CS1503:无法将“method group”转换为“System.Action<byte, byte, bool[,]>”
问题核心
你的代码触发错误的根本原因是委托签名和目标方法的签名不匹配:
- 内部定义的
eraser方法,第三个参数带ref修饰符:ref bool[,] device_results - 但
ForAllDevicesResults方法接收的委托类型是Action<byte, byte, bool[,]>,这个内置委托的第三个参数是值传递,没有ref关键字,两者无法兼容。
两种修正方案
方案一:自定义带ref参数的委托(适用于需要修改数组引用的场景)
因为.NET内置的Action系列泛型不支持带ref/out的参数,所以需要自己定义匹配的委托类型:
using System; public class Program { // 自定义匹配ref参数的委托 delegate void DeviceAction(byte BoardNo, byte DeviceNo, ref bool[,] device_results); void EraseGoodBlocks(bool OverridePreviousTests, ref bool[,] DeviceResults) { ForAllDevicesResults(eraser, ref DeviceResults); void eraser(byte BoardNo, byte DeviceNo, ref bool[,] device_results) {} } void ForAllDevicesResults(DeviceAction action, ref bool[,] result){ for (byte Board = 0; Board < 4; Board++){ for (byte Device = 0; Device < 16; Device++){ action(Board, Device, ref result); // 调用时必须加ref } } } }
方案二:移除方法参数的ref修饰符(适用于仅修改数组元素的场景)
多维数组是引用类型,即使不用ref,修改数组内的元素值也会影响原数组。如果你的eraser不需要让传入的数组变量指向新的数组对象,直接去掉ref即可:
using System; public class Program { void EraseGoodBlocks(bool OverridePreviousTests, ref bool[,] DeviceResults) { ForAllDevicesResults(eraser, ref DeviceResults); void eraser(byte BoardNo, byte DeviceNo, bool[,] device_results) {} // 移除ref } void ForAllDevicesResults(Action<byte, byte, bool[,]> action, ref bool[,] result){ for (byte Board = 0; Board < 4; Board++){ for (byte Device = 0; Device < 16; Device++){ action(Board, Device, result); } } } }
额外说明
- 区分
ref的使用场景:只有当你需要修改变量本身的引用(比如让DeviceResults指向一个新的多维数组)时,才需要用ref;如果只是修改数组里的元素值,不需要ref也能生效。
内容的提问来源于stack exchange,提问作者Gerhard
相关产品推荐
相关产品推荐

