c#检查我对赋值的理解是否正确

本文关键字:是否 检查 赋值 | 更新日期: 2023-09-27 18:18:13

所以我正在学习c#,并且我在编写程序时遇到了一点麻烦。我只是想检查一下我对变量赋值的理解是否正确。下面的行为和我想的一样吗?

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.

c#检查我对赋值的理解是否正确

我想稍微改变一下你的一些评论,至少对我来说有点不准确(其他评论都是好的):

// 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; 
...