简体   繁体   English

为什么引用类型变量的行为类似于值类型变量

[英]Why is reference type variable behaves like value type variable

So, I have a reference type which is Weapon:所以,我有一个引用类型,它是武器:

class Weapon
{
    //Some properties that are both value type and reference type
}

And I have another class to hold an array of weapons and fire an event when the current weapon changes:我还有另一个类来保存一系列武器并在当前武器发生变化时触发一个事件:

class WeaponManager
{
    Weapon[] weapons;
    Weapon currentWeapon;

    Weapon CurrentWeapon
    {
       get => currentWeapon;
       set
       {
           Weapon oldWeapon = currentWeapon;
           currentWeapon = value;
           OnWeaponChanged?.Invoke(oldWeapon, currentWeapon);
       }
    }
}

I declare the oldWeapon variable and assign it to currentWeapon in order to hold the data.我声明了 oldWeapon 变量并将其分配给 currentWeapon 以保存数据。 My question is that I believe since the Weapon is a reference type, when I reassign currentWeapon, oldWeapon should also change.我的问题是我相信因为 Weapon 是一个引用类型,当我重新分配 currentWeapon 时,oldWeapon 也应该改变。 But for some reason assignements I make to currentWeapon variable doesn't effect the oldWeapon.但是由于某种原因,我对 currentWeapon 变量进行的赋值不会影响 oldWeapon。 Is there some sort of thing going around that I'm not aware of or did I misunderstand something?是否有某种我不知道或我误解了什么?

Note: Weapon class is deriving from another class which has at least one string in it but I'm not sure if that's the issue.注意:武器类源自另一个类,其中至少有一个字符串,但我不确定这是否是问题所在。

There is something going on that you're not misunderstanding.有一些事情正在发生,你没有误解。 Each reference you establish to an object in memory is its own reference, it is not a reference to another reference to the object (it is not a chain)您对内存中的对象建立的每个引用都是它自己的引用,它不是对该对象的另一个引用的引用(它不是链)

//if you do
currentWeapon = "a sword"
oldWeapon = currentWeapon

//then you have this
oldWeapon --> "a sword" <-- currentWeapon

//you do not have this
oldWeapon  --> currentWeapon --> "a sword"


//if you then do this
currentWeapon = "a gun"

//then you have this
oldWeapon --> "a sword"      currentWeapon --> "a gun"

//you do not have this
oldWeapon  --> currentWeapon --> "a gun"

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

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