繁体   English   中英

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

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

所以,我有一个引用类型,它是武器:

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

我还有另一个类来保存一系列武器并在当前武器发生变化时触发一个事件:

class WeaponManager
{
    Weapon[] weapons;
    Weapon currentWeapon;

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

我声明了 oldWeapon 变量并将其分配给 currentWeapon 以保存数据。 我的问题是我相信因为 Weapon 是一个引用类型,当我重新分配 currentWeapon 时,oldWeapon 也应该改变。 但是由于某种原因,我对 currentWeapon 变量进行的赋值不会影响 oldWeapon。 是否有某种我不知道或我误解了什么?

注意:武器类源自另一个类,其中至少有一个字符串,但我不确定这是否是问题所在。

有一些事情正在发生,你没有误解。 您对内存中的对象建立的每个引用都是它自己的引用,它不是对该对象的另一个引用的引用(它不是链)

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