Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

c# - ArrayList of object references

Having a user defined class, like this:

class Foo
    {
        public int dummy;

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

And having then something like this:

ArrayList dummyfoo = new ArrayList();

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

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

How much is a.dummy?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Why ->

  Consider var arr = new ArrayList();

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).

Now at the time of calling,

example ->    DummyMethod(arr) , 

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.

If you want to avoid this behavior you have to create copy/clone of the object.

Example:

Instead of

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

Use

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...