将数组作为参数传递 [英] Passing arrays as parameter

查看:107
本文介绍了将数组作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们修改方法内部作为参数传递的数组的内容,则修改是在参数的副本上而不是原始参数上进行的,因此结果不可见.

If we modify the content of the array passed as parameter inside a method the modification is done on the copy of the argument instead of the original argument hence the result is not visible.

当我们调用具有引用类型实参的方法时,会发生什么过程?

What is the process that happens when we call method that have reference type argument?

这是我要问的代码示例

      using System;

namespace Value_Refrence_Type
{
    class Program
    {
        public static void Main()
        {
            int[] callingarray = { 22, 200, 25485 };
            abc(callingarray);
            Console.WriteLine("This is callingarray");
            foreach (int element in callingarray)
                Console.WriteLine(element);
        }



        //method parameter
        static void abc(int[] calledarray)
        {
            Console.WriteLine("Method Called--------");
            foreach (int element in calledarray)
                Console.WriteLine(element);

            //Here on changing the value of elements of calledarray does't afftect the value of element of callingarray
            //if both refrences to same memory location then the value needs to change, which is not happening here
            calledarray = new int[] {55, 54, 65};
            foreach (int element in calledarray)
                Console.WriteLine(element);
        }

    }
}

推荐答案

不,那是不正确的.

默认情况下,参数在C#中按值传递,这意味着您将获得变量的副本.但是,重要的是要意识到,复制的内容只是变量,而不一定是对象.如果变量具有引用类型(例如数组),则该变量实际上只是对象所在的内存地址的指针".因此,当您将所述变量传递给方法调用时,引用被复制为yes,但仍指向原始变量所引用的完全相同的对象.

Arguments are passed by value by default in C#, which means you get a copy of the variable. But it's important to realize that what is copied is just the variable, not necessarily the object; if the variable holds a reference type (an array for example) then the variable is really just a "pointer" to a memory address where the object lives. So when you pass said variable to a method call, the reference is copied yes, but it still points to the exact same object the original variable refers to.

当参数为值类型时,情况大不相同.在这种情况下,变量本身包含对象,因此您将获得预期的行为.

Things are very different when the argument is a value type. In that case the variable itself holds the object and therefore you'd get the behavior you seem to be expecting.

这篇关于将数组作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆