2015-10-19 33 views
3

所以我在学习C#,而且我正在写一个程序时遇到了一些麻烦。我只是想检查我是否理解变量赋值权。下列行为是否像我想的那样?C#check我很理解分配权

SomeObject someObject; // declares a SomeObject object called someObject 
SomeObject someReference; // declares a SomeObject object called someReference 
SomeObject someOtherObject; // declares a SomeObject object called someOtherObject 

someObject = new SomeObject(); // initialises a new SomeObject object into someObject using SomeObject's contructor 
someOtherObject = new SomeObject(); // initialises a new SomeObject object into someOtherObject using SomeObject's constructor 
someReference = someObject; // someReference is now a reference pointing to the same place as someObject 

someReference.attribute = value; // sets someReference's attribute attribute to value. someObject.attribute is also now value 

someReference = someOtherObject; // someReference now points to someOtherObject instead of someObject 
someReference.attribute = value2; // someOtherObject.attribute is now value2. someObject.attribute is unaffected 

someReference = null; // sets someReference to be a null reference. someObject and someOtherObject are unaffected. 
+7

是的,你的理解是正确的。但是我想你在问你之前已经自己检查过了,是不是? –

+0

如果您“编写程序时遇到困难”,请创建一个能够重现问题的[mcve]。 – CodeCaster

+1

作为**“分配”**的含义,请注意标题**“是一个约见某人的秘密,通常是由恋人制作的。”_ – Enigmativity

回答

1

我会稍微改变你的一些评论说,似乎有点不准确的,至少对我来说(别人的意见都是正确的):

// declares a field (if it's in class) or a variable (if it's inside method) 
// of type SomeObject that will later work with SomeObject instance 

SomeObject someObject; 

... 

// instantiates a new SomeObject instance (including creation of object on heap, 
// pointer to this object and running object constructor). 
// It also makes someObject point to this newly created object. 

someObject = new SomeObject(); 
... 

// sets new value for someReference's 'attribute' field (or property) 

someReference.attribute = value; 

... 
+0

@CodeCaster感谢您的评论,更新了我的回答 – Fabjan