2015-10-19 29 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