2015-10-06 60 views
0

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

比如我想在的位置 'TutGrass'

Location of tutgrass

总是被设置为CharacterX和CharacterY

enter image description here

所以每当CharacterX和CharacterY的值更改位置的TutGrass将改变。

+0

只需使用属性,而不是。 –

+0

添加代码而不是截图,但通常情况下,您会创建一个由属性共享的支持字段。 –

+0

只需使用属性。 - 请说明 –

回答

3

你可以使用属性来改变位置的值:

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

这样的定位和字符的值绑在一起(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 
+0

hmmm sooooo这意味着我可以做一些像TutGrass.location.x = CharacterX.Location.X? –

+0

查看我的编辑。如果你在'get'和'set'中放置了一个断点,这对你的理解可能会有所帮助。 – MikeH

+0

好吧即时通过他们 –

相关问题