开发者

Problem with copying arrays

I have the following code:

string[] firstArray = { "bla bla开发者_开发百科", "bla bla", "bla bla"};   
string[] secondArray = {"aaaaaaaaaaaa", "aaaaaaaaaaa", "aaaaaaaaa"};    

string[] newArray = firstArray;

firstArray = secondArray;

foreach (string item in newArray)
{
     Console.WriteLine(item);
} 

This code gives the following results:

bla bla

bla bla

bla bla

I can't understand why the newArray has the same conntent after I assign a different instance to the firstArray. Please help me.


You're assigning references to arrays, not the arrays themselves.

string[] firstArray = { "bla bla", "bla bla", "bla bla"};   

firstArray has a reference to the blabla array.

string[] secondArray = {"aaaaaaaaaaaa", "aaaaaaaaaaa", "aaaaaaaaa"};    

secondArray has a reference to the aaaaaaaaaaaa array.

string[] newArray = array;

I guess there was a array = firstArray somewhere. newArray holds a reference to the same array as firstArray (blabla).

array = secondArray;

array holds a reference to the same array as secondArray (aaaaaaaaaaaa).

foreach (string item in newArray)

newArray still holds a reference to the blabla array, so that prints.


Because you're changing only references to arrays. So newArray will reference to firstArray and then you change a firstArray reference but newArray still reference to the previous blabla array.


string[] newArray = array;
array = secondArray;

array is an undeclared, undefined variable. I do not see how you can either assign newArray to it, or set it to secondArray.

You also refer to both firstArray and firstarray, which will not work.


I am assuming when you write 'array' in your code, you mean 'firstArray'.

There is no change because you are not assigning to newArray at all. newArray is a reference; when you type string[] newArray = array, it is pointing to the same address as firstArray. When you assign firstArray to secondArray, you are just changing where firstArray points to. This does not changes where newArray points to.

The basic concept is that reference variables in C# refers to a memory address. It's not the idea of equal. That is, a = b, and you set b = c, that does not changes a. It's more proper to think of it as

a = address 1
b = address 2
c = address 3

when you do a = b,

a = address 2
b = address 2
c = address 3

and when you do b = c

a = address 2
b = address 3
c = address 3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜