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

C#静态类实现冒泡排序时报错:属性或索引器不可作为out/ref参数传递

报错原因与解决方案

报错根因

报错提示:A property or indexer may not be passed as an out or ref parameter

  • 核心原因:List<T>的索引器属于属性,本质是get_Item(int index)/set_Item(int index, T value)方法的语法糖,不是可直接寻址的内存变量,C#语法不允许将属性/索引器作为ref/out参数传递。
  • 你提到类改为非静态时可正常运行,和类是否为静态没有关联,大概率是非静态版本使用数组作为参数,数组的索引器是可寻址的变量,天然支持ref传递。

修复方案

优先选择兼容性最高的调整方案:修改Swap方法的入参,改为传入List实例和要交换的两个索引位置,避免直接传递索引器的ref引用。

修正后的完整代码如下:

public static class BubbleSort
{
    public static void Sort(List<int> arr)
    {
        for (int i = 0; i < arr.Count - 1; i++)
        {
            bool flag = true;
            for (int j = 0; j < arr.Count - i - 1; j++)
            {
                if (arr[j] > arr[j + 1])
                {
                    Swap(arr, j, j + 1);
                    flag = false;
                }
            }

            if (flag)
                break;
        }
    }

    private static void Swap(List<int> arr, int index1, int index2)
    {
        int temp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = temp;
    }
}

补充说明:原代码中的类名BubleSort为拼写错误,标准拼写为BubbleSort,上述代码已同步修正。

可选兼容方案(仅支持.NET Core 2.0/.NET 5及以上版本)

如果不想修改Swap方法的定义,可使用CollectionsMarshal.AsRef方法直接获取List元素的内存引用,调用代码修改为:

Swap(ref CollectionsMarshal.AsRef(arr, j), ref CollectionsMarshal.AsRef(arr, j + 1));

内容的提问来源于stack exchange,提问作者Filip Stoyanov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:54:04