c# - 按引用调用未按预期工作

标签 c# arrays ref

在微软web的例子中有如下代码:

class TestRef
{
    static void FillArray(ref int[] arr)
    {
        // Create the array on demand: 
        if (arr == null)
        {
            arr = new int[10];
        }
        // Fill the array:
        arr[0] = 1111;
        arr[4] = 5555;
    }
}

如果我删除 if (arr == null) 行,错误输出将是 0 0 0 0 0 而不是 1 2 3 4 5 。为什么?

最佳答案

这是因为您通过 ref 传递,这意味着您正在更改 main 方法中该变量的指针。

您正在将其分配给一个新的 int[],该 int[] 填充了 int 的默认值,即 0

关于c# - 按引用调用未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24156222/

相关文章:

无论数组大小如何,Java 多数组递归

ios - 根据属性比较并返回不同的 swift 数组对象

Javascript对象显示为空,但点击后看到有值但无法访问

c# - 按值或引用返回?

c# - 从 CSV 文件中读取最新行

c# - Web 客户端异常 : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel

c# - 查看一组实数的快速方法

c# - 表单构造函数与 Form_Load

arrays - 在 postgresql 9.4 或 9.5 中查询 json 对象的嵌套数组中的元素

C#:构造函数中的奇怪引用的行为类似于 "virtual field"