对象引用的 ArrayList [英] ArrayList of object references

查看:66
本文介绍了对象引用的 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个用户定义的类,像这样:

Having a user defined class, like this:

class Foo
    {
        public int dummy;

        public Foo(int dummy)
        {
            this.dummy = dummy;
        }
    }

然后有这样的事情:

ArrayList dummyfoo = new ArrayList();

Foo a = new Foo(1);
dummyfoo.add(a);

foreach (Foo x in dummyfoo)
    x.dummy++;

a.dummy 多少钱?

How much is a.dummy?

如何创建我的 ArrayList 以便 a.dummy 等于 2,这意味着我的 ArrayList 基本上包含指向我的对象的指针,而不是副本.

How can i create my ArrayList so that a.dummy equals 2, meaning that my ArrayList contains basically pointers to my objects and not copies.

推荐答案

它已经是 2,因为数组/集合(准确地说是任何 .NET 类/引用类型)默认通过引用传递.

It is already 2, as Array/Collections (to be precise any .NET Class/reference type) are passed by reference by default.

实际上引用变量是按值传递的,但表现得就像是按引用传递一样.

In fact the reference variable is passed by value, but behaves as if passed by reference.

为什么 ->

  Consider var arr = new ArrayList();

上面的语句首先创建了一个ArrayList对象,并给arr赋值了一个引用.(这对于任何类都是类似的,因为类是引用类型).

The above statement first creates an ArrayList object and a reference is assigned to arr. (This is similar for any Class as class are reference type).

现在在打电话的时候,

example ->    DummyMethod(arr) , 

引用是按值传递的,即即使参数被分配给方法内的不同对象,原始变量也保持不变.
但是由于变量指向(引用)同一个对象,对底层指向对象所做的任何操作都会反映在被调用方法之外.
在您的示例中,对每个所做的任何修改都将反映在 arrayList 中.

the reference is passed by value, that is even if the parameter is assigned to a different object within the method, the original variable remains unchanged.
But as the variable points(refer) to same object, any operation done on underlying pointed object is reflected outside the called method.
In your example, any modification done in for each will be reflected in the arrayList.

如果您想避免这种行为,您必须创建对象的副本/克隆.

示例:

代替

foreach (Foo x in dummyfoo)
        x.dummy++;

使用

foreach (Foo x in (ArrayList)dummyfoo.Clone())
        x.dummy++;

这篇关于对象引用的 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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