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

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

问题描述

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

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# 中默认是按值传递的,这意味着你会得到一个变量的副本.但重要的是要意识到复制的只是变量,不一定是对象;如果变量包含引用类型(例如数组),那么变量实际上只是指向对象所在的内存地址的指针".因此,当您将所述变量传递给方法调用时,引用会被复制,但它仍然指向原始变量所引用的完全相同的对象.

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天全站免登陆