为什么引用类型变量的行为像值类型变量
Why is reference type variable behaves like value type variable
所以,我有一个参考类型,它是武器:
class Weapon
{
//Some properties that are both value type and reference type
}
我还有另一个 class 来保存一系列武器并在当前武器更改时触发事件:
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。是否发生了某种我不知道的事情,或者我误解了什么?
注意:武器 class 派生自另一个 class,其中至少有一个字符串,但我不确定这是否是问题所在。
有些事情你没有误会。您在内存中建立的对对象的每个引用都是它自己的引用,它不是对该对象的另一个引用的引用(它不是链)
//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"
所以,我有一个参考类型,它是武器:
class Weapon
{
//Some properties that are both value type and reference type
}
我还有另一个 class 来保存一系列武器并在当前武器更改时触发事件:
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。是否发生了某种我不知道的事情,或者我误解了什么?
注意:武器 class 派生自另一个 class,其中至少有一个字符串,但我不确定这是否是问题所在。
有些事情你没有误会。您在内存中建立的对对象的每个引用都是它自己的引用,它不是对该对象的另一个引用的引用(它不是链)
//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"