2015-10-06 28 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

好吧即時通過他們 –

相關問題