You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#泛型方法传参报错:bool无法赋值给System.Func<bool>

问题原因与解决方法:Argument type 'bool' is not assignable to parameter type 'System.Func'

错误核心原因

你调用IterateThroughArray时传入的GetRandomBool()是执行该函数后返回的bool值,但方法的第二个参数要求的是Func<bool>类型的委托——也就是一个可以返回bool的函数本身,而非函数执行后的结果。

Func<T>是C#中的委托类型,代表「无参数、返回T类型值」的方法。当你写GetRandomBool()时,C#会立即执行这个方法并拿到它的bool返回值,但IterateThroughArray需要的是这个方法的引用,让它在循环内部重复调用,而不是一次性传入一个固定的bool值。

修正方案

  1. 调整方法调用方式:去掉GetRandomBool后面的括号,直接传入方法引用:
IterateThroughArray(_gameOfLifeGrid, GetRandomBool);
  1. 修复循环逻辑bug:你的嵌套循环内层条件写错了,应该用y < array.GetLength(1)来遍历第二维度,否则会导致y维度遍历错误甚至数组越界:
public void IterateThroughArray<T>(T[,] array, Func<T> myAction)
{
    for (var x = 0; x < array.GetLength(0); x++)
    {
        for (var y = 0; y < array.GetLength(1); y++)
        {
            array[x,y] = myAction();
        }
    }
}

内容的提问来源于stack exchange,提问作者Max Heinze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 14:21:31