2012-05-05 55 views
2

我寫這樣的屬性(表示方向爲我XNA遊戲對象):分配和方法調用順序

public Vector2 Direction 
{ 
    get { return direction; } 
    protected set 
    { 
     (direction = value).Normalize(); // *** 
     angle = MathHelper.WrapAngle((float)Math.Atan(direction.X/direction.Y)); 
    } 
} 

設置其表示對象的方向在角並且同時在歸一化矢量兩個等價的字段。

開始遊戲失敗,因爲線路標有***失敗。它沒有標準化向量。
我改變了這一行:

direction = value; 
direction.Normalize(); 

,它工作正常,爲什麼?
我假設在標有***的行中,第一個操作是指定,然後正常化方向。但事實並非如此。

_ __ __ __ ___
正常化()是從方法Vector2類。

// 
// Summary: 
//  Turns the current vector into a unit vector. The result is a vector one unit 
//  in length pointing in the same direction as the original vector. 
public void Normalize(); 
+1

請爲您正在討論的語言添加標籤。 – Mat

+1

請包括拋出的異常/錯誤消息導致遊戲失敗。 – StellarEleven

+0

「遊戲失敗」我的意思是遊戲的邏輯沒有正確更新。 –

回答

4

我假設Vector2是一個結構或值類型,這意味着它是通過值傳遞而不是通過引用。當您將值指定給方向時,您正在將方向設置爲值的副本。此外,表達式(direction = value)返回的對象是副本,而不是方向上的同一個實例。您在一個永遠不會存儲在setter塊之外的對象上調用Normalize。

出於同樣的原因,您不能在類上的屬性getter返回的結構上調用方法或設置屬性。例如,如果示例中的屬性位於名爲Monkey的類中,請注意:

Monkey m = new Monkey(); 
m.Direction = new Vector2(...); 
m.Direction.X = 2; // This will not compile. 
m.Direction.Normalize(); // This will not do what you expect.