Today a little bit of free, originally want to see what the Web page, helpless boss sits, had to open the "CLR VIA C #"
Some places are a bit confused, ready to knock code to try, open the learning project, suddenly found that there was a before see "Deep C # Memory management to analyze value types & reference types, boxing & unboxing, stacking the differences between several conceptual combinations" legacy issues
The code is like this.
int i = 4;
Object o = i;
Object O2 = O;
Console.WriteLine (ReferenceEquals (O, O2)); True
o = 8;
Console.WriteLine (ReferenceEquals (O, O2)); False
Console.WriteLine ("I={0}, O={1}, o2={2}", I, O, O2);//4, 8, 4, why?
The results of the original post also have, but why, do not understand, just know and boxing a bit of a relationship (int to the object of course to boxing). The reference, the 4th line above, shows that the two point to the same object, but after O=8, the two are not the same object. That's why.
Helpless sacrifice out of ildasm, this back to the sky (omit Console.WriteLine code)
il_0001: ldc.i4.4
il_0002: stloc.0
il_0003: ldloc.0 il_0004
: box [mscorlib] System.Int32
il_0009: stloc.1
il_000a: ldloc.1 il_000b:
stloc.2 il_000c: ldc.i4.8
il_000d: box [Mscorlib]system.int32
il_0012: stloc.1
1. Create a constant with a value of 4, into the stack
2. Out stack, put the value into the first memory variable (int i = 4)
3. Put the first memory variable into the stack
4. Boxing (Object o = i)
5. Out stack, put O address into the second memory variable
6. Put the second memory variable into the stack
7. Out stack, place address into third memory variable (address of O) (object O2 = O)
8. Create a constant with a value of 8, into the stack
9. Packing
10. Out stack, put the boxed address into the second memory variable (o = 8)
So it seems clear that the address of O2 and O is markedly different, because there is a boxing operation for 8 in O=8, only the address saved in the second memory variable is modified, and the third memory variable remains the last boxed 4 o'clock address, so o=8, o2=4
By the way, string.
A string is immutable, that is, after a string object is created, if its contents are modified, a new string object is created, in other words, the address changes. The interpretation in CLR VIA C # is string pooling, and all string objects with the same content will point to the same string object in the same metadata. So the following code
String S1 = "Hello";
String s2 = "Hello";
Console.WriteLine (Object.referenceequals (S1, S2));
The result is true