为什么数组的引用没有改变? [英] Why the reference of an array is not changing?

查看:79
本文介绍了为什么数组的引用没有改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅代码段...

Please see the code snippet...

class a
   {
       int[] cr=new int[10];
       public void add(int[] br)
       {
           cr[0] = 111;
           br=cr;
       }
   }
   class Program
   {

       static void Main(string[] args)
       {
              int[] ar = new int[10];
              ar[0] = 55;
           a obj = new a();
           obj.add(ar);
           Console.WriteLine(ar[0]);

       }



为什么"ar []"的引用未更改为"cr []"?



Why the reference of the ''ar[]'' is not changing to ''cr[]'' ?

推荐答案

因为在您传递值时传递了ar希望通过引用传递它.
Because you are passing ar by value when you would want to pass it by reference.


class a
   {
       int[] cr=new int[10];      //think cr address is [3000]
       public void add(int[] br)   //getting 2000=>br
       {
           cr[0] = 111;           
           br=cr;                  //br=cr means br=3000,it doesn't mean ar=3000
       }                           //because it is value, not reference
   }
   class Program
   {

       static void Main(string[] args)
       {
              int[] ar = new int[10];   //think ar address is [2000] 
              ar[0] = 55;
           a obj = new a();
           obj.add(ar);      //passing 2000
           Console.WriteLine(ar[0]);

       }


尝试一下:

try this:

class a
   {
       int[] cr=new int[10];
       public int[] add(/*int[] br*/)
       {
           cr[0] = 111;
           //br=cr;
           return cr;
       }
   }
   class Program
   {
 
       static void Main(string[] args)
       {
              int[] ar = new int[10];
              ar[0] = 55;
           a obj = new a();
           //obj.add(ar);
           arr = obj.add();
           Console.WriteLine(ar[0]);
 
       }



我很快又很脏了,但是我认为这是因为br不会 out 该函数.如果要传递参数并进行更改,则需要使用ref或out关键字(请参见MSDN)

希望对您有所帮助.



I did it quick and dirty, but I think it is because br is not coming out the function. if you want to pass an argument and change it, you need to use the ref or out keyword (see MSDN)

hope this helps.


这篇关于为什么数组的引用没有改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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