简体   繁体   English

对C#中的对象引用感到困惑

[英]Confused about object references in C#

Ok, 好,

I have a matrix of enemies Enemy enemyGrid[x, y] 我有一个敌人Enemy enemyGrid[x, y]矩阵Enemy enemyGrid[x, y]

Then, in my code I get an instance of one of the enemies by calling Enemy tmp = enemyGrid[a, b] 然后,在我的代码中,我通过调用Enemy tmp = enemyGrid[a, b]得到了一个敌人的实例。

But if I change a property in tmp it is not reflected the next time I load the object from the matrix into the the same object tmp. 但是,如果我更改了tmp中的属性,则下次将对象从矩阵加载到同一对象tmp中时,该属性不会反映出来。

Each time I am finished with tmp I need to make it = null to have the change reflected into the object in the gird? 每次完成tmp时,我都需要将其设置= null才能将更改反映到网格中的对象中?

Why is that? 这是为什么? I thought that tmp would just hold a reference to the object and changes would be made directly in the main object. 我认为tmp只会保留对该对象的引用,而更改将直接在主对象中进行。

Thanks. 谢谢。

CODE UPDATE: 代码更新:

Populating the grid: 填充网格:

Enemy [,] spriteGrid = new Enemy[countCols, countRows];
spriteGrid[x, y] = new Enemy();

Access an object and change properties: 访问对象并更改属性:

Enemy tmp = spriteGrid[i, j];

tmp.canShoot = true;
tmp.Update(gameTime, game.Window.ClientBounds);
tmp.canShoot = false;

The last line (canShoot = false) does not reflect into the object stored in the grid. 最后一行(canShoot = false)不会反映到存储在网格中的对象中。

The line 线

Enemy tmp = enemyGrid[a, b]

does not create a copy of the object in your matrix. 在你的矩阵不会创建对象的副本。 It creates an alias to the same object instance. 它为同一对象实例创建别名。 Changes to tmp do affect the instance in the grid that they alias. tmp的更改确实会影响其别名的网格中的实例。

Please post a short, complete code snippet that demonstrates the issue you are experiencing. 请发布简短的完整代码段,以演示您遇到的问题。

UPDATE 更新

In your sample, you set 在您的示例中,您设置了

tmp.canShoot = true;

but then 但是之后

tmpEnemy.canShoot = false;

Two different variables. 两个不同的变量。

Update 2 更新2

@Amry's comment is also accurate... if Enemy is a struct instead of a class , you would see this very behavior. @Amry的评论也很准确...如果Enemy是一个结构而不是一个 ,您将看到这种行为。 That is because struct is a value type , meaning the assignment does create a copy rather than an alias. 那是因为struct是一个值类型 ,这意味着赋值确实会创建一个副本而不是别名。

Except for very special cases, you should never use a struct that is mutable (that is, a struct whose value can change after it is initially created). 非常特殊的情况外, 永远不要使用可变的结构(即,其值在最初创建后可以更改的结构)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM