简体   繁体   中英

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. My question is that I believe since the Weapon is a reference type, when I reassign currentWeapon, oldWeapon should also change. But for some reason assignements I make to currentWeapon variable doesn't effect the 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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