简体   繁体   English

通过引用致电无法正常工作

[英]Call by reference not working as expected

In the example of Microsoft's web there are below codes: 在Microsoft网站的示例中,有以下代码:

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 I delete the line of if (arr == null) , the error output will be 0 0 0 0 0 not 1 2 3 4 5 . 如果删除if (arr == null) ,则错误输出将为0 0 0 0 0而不是1 2 3 4 5 Why? 为什么?

This is because you are passing by ref this means that you are changing the pointer for that variable in the main method. 这是因为您通过ref传递,这意味着您正在main方法中更改该变量的指针。

You are assigning it to a new int[] that is filled with the default value of int which is 0 您正在将其分配给一个新的int[] ,该int的默认值是0

its happening because when you put your code as it is it mean you are passing your intArray to the method but when you remove the lines as you have mentioned in this case new int[] is assigned to variable which will fill default 0 in your array. 发生这种情况的原因是,按原样放置代码意味着将intArray传递给方法,但是如本例所述,当删除行时,会将新的int []分配给变量,该变量将填充数组中的默认0 。

this line arr = new int[10]; 这行arr = new int[10]; is assigning new int[] when you remove conditions. 删除条件时分配新的int []。

As documented in the official site :- 如官方网站中所述:

A ref parameter of an array type may be altered as a result of the call. 调用的结果可能会更改数组类型的ref参数。 For example, the array can be assigned the null value or can be initialized to a different array. 例如,可以为数组分配空值,也可以将其初始化为其他数组。

Here in FillArray function you are passing the array by reference FillArray函数中,您通过引用传递数组
but when you remove the if block 但是当您删除if块时
you re-initialize the array 您重新初始化数组

when you initialize a value type array the elements take default value of the value type 初始化值类型数组时,元素采用值类型的默认值
In this case it is int which have default value 0 在这种情况下,其int默认值为0

You need to understand pass by value vs pass by reference in C# 您需要了解C#中按值传递与按引用传递
http://www.programminginterviews.info/2011/05/pass-by-value-versus-reference-in-c.html http://www.programminginterviews.info/2011/05/pass-by-value-versus-reference-in-c.html

also value type vs ref type 也值类型vs引用类型
http://www.albahari.com/valuevsreftypes.aspx http://www.albahari.com/valuevsreftypes.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM