有没有办法让对象变量另一个变量?
例如,我想在TutGrass'
上找到位置始终设置为CharacterX和CharacterY
因此,只要CharacterX和CharacterY的值发生变化,TutGrass的位置也会发生变化。
答案 0 :(得分:3)
您可以使用属性修改位置值:
public int CharacterX
{
get
{
return Location.X;
}
set
{
Location = new Point(value, Location.Y);
}
}
通过这种方式,Location和Character的值被绑定在一起(Location.X将保存此示例中的值)。如果需要,可以让另一个中间变量保持该值。通常是private
。
在您的代码中,您可以修改Location.X
或CharacterX
,它们都会更新:
Location.X = 5; //Sets the value of Location.X to 5
int testValue = CharacterX; //since CharacterX will return the value of Location.X testValue is assigned 5
CharacterX = 6;//Sets the value of Location.X to 6. CharacterX never really holds a value, just assigns it to Location.X