有没有办法让对象的变量设置为另一个变量?

时间:2015-10-06 17:58:11

标签: c#

有没有办法让对象变量另一个变量?

例如,我想在TutGrass'

上找到位置

Location of tutgrass

始终设置为CharacterX和CharacterY

enter image description here

因此,只要CharacterX和CharacterY的值发生变化,TutGrass的位置也会发生变化。

1 个答案:

答案 0 :(得分:3)

您可以使用属性修改位置值:

public int CharacterX
{
  get
  {
    return Location.X;
  }
  set
  {
    Location = new Point(value, Location.Y);
  }
}

通过这种方式,Location和Character的值被绑定在一起(Location.X将保存此示例中的值)。如果需要,可以让另一个中间变量保持该值。通常是private

在您的代码中,您可以修改Location.XCharacterX,它们都会更新:

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
相关问题