所以,我有一个引用类型是Weapon:
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以便保存数据。我的问题是,我相信由于武器是参考类型,因此当我重新分配currentWeapon时,oldWeapon也应该更改。但是出于某种原因,我对currentWeapon变量的赋值不会影响oldWeapon。是否有某种我不知道的事情发生或者我误解了?
注意:武器类是从另一个至少包含一个字符串的类派生的,但是我不确定这是否是问题所在。
答案 0 :(得分:4)
有些事情正在发生,您不会误会。您对内存中的对象建立的每个引用都是其自己的引用,不是对对象的另一个引用的引用(不是链)
//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"