我想知道当我们创建一个对象" a"时会发生什么,然后做一个参考" b"然后我们用" a"创建一个新对象,56会发生什么?我怎么理解" a"失去对56的引用,创建了对20的新引用。制作" b"唯一持有人参考56。
class SingleDigit
{
public int Digit { get; set; }
public SingleDigit(int b)
{
Digit = b;
}
}
SingleDigit a = new SingleDigit(56); // creat new object with int 56
SingleDigit b = a; // make a reference to a
b.Digit -= 20; // both a and b's digit is subtracted
a = new SingleDigit(20); // What happens here ? Does a lose its reference to 56 ?
答案 0 :(得分:2)
//Create a reference location for variable a. Assign it value 56.
SingleDigit a = new SingleDigit(56);
// Create a new object b and give it reference of a's object location.
//So, b.Digit is also 56.
SingleDigit b = a;
//Decrement 20 from b.Digit.
//It decrements from a.Digit as well since both
//refer to same memory object. So, both become 36.
b.Digit -= 20; // both a and b's digit is subtracted
// b holds up to original memory location.
//A new memory location has a new object created and
//its location is provided to variable a.
//a.Digit is now 20, and not 36.
a = new SingleDigit(20); //a loses its reference to 36
答案 1 :(得分:1)