2010-04-08 74 views
1

我正在開發遊戲。我想讓遊戲實體擁有自己的Damage()函數。當被調用時,他們會計算他們想造成多大的損害做:修復錯誤:無法通過表達式引用類型

public class CombatantGameModel : GameObjectModel 
{ 
    public int Health { get; set; } 

    /// <summary> 
    /// If the attack hits, how much damage does it do? 
    /// </summary> 
    /// <param name="randomSample">A random value from [0 .. 1]. Use to introduce randomness in the attack's damage.</param> 
    /// <returns>The amount of damage the attack does</returns> 
    public delegate int Damage(float randomSample); 

    public CombatantGameModel(GameObjectController controller) : base(controller) {} 
} 

public class CombatantGameObject : GameObjectController 
{ 
    private new readonly CombatantGameModel model; 
    public new virtual CombatantGameModel Model 
    { 
     get { return model; } 
    } 

    public CombatantGameObject() 
    { 
     model = new CombatantGameModel(this); 
    } 
} 

然而,當我嘗試調用該方法,我得到一個編譯錯誤:

/// <summary> 
    /// Calculates the results of an attack, and directly updates the GameObjects involved. 
    /// </summary> 
    /// <param name="attacker">The aggressor GameObject</param> 
    /// <param name="victim">The GameObject under assault</param> 
    public void ComputeAttackUpdate(CombatantGameObject attacker, CombatantGameObject victim) 
    { 
     if (worldQuery.IsColliding(attacker, victim, false)) 
     { 
      victim.Model.Health -= attacker.Model.Damage((float) rand.NextDouble()); // error here 
      Debug.WriteLine(String.Format("{0} hits {1} for {2} damage", attacker, victim, attackTraits.Damage)); 
     } 
    } 

的錯誤是:

'Damage': cannot reference a type through an expression; try 'HWAlphaRelease.GameObject.CombatantGameModel.Damage' instead

我在做什麼錯?

回答

2

在調用它之前,您需要將一個函數與該代理關聯。

在這裏你不需要一個委託 - 使用你的代碼,你最好將你的Damage函數作爲一個接口的實現,或者在基類GameObjectModel類中聲明爲抽象的(或虛擬的)以便派生類可以(或必須)覆蓋它。

+2

+1此處不需要委託,我同意。 – 2010-04-08 00:40:39

+0

這取決於。如果您希望計算在運行時非常靈活和可互換,委託通常是更簡單,更直接的選擇。 – 2010-04-08 00:44:06

1

您實際上聲明瞭一個名爲Damage的嵌套委託類型,而不是該類型的實例。把它看作是一個類和一個類的一個實例之間的區別。

要實際使用您的委託,您必須聲明一個字段,屬性或事件來保存它。

例如:

// note that the delegate can be declared either in a class or outside of it. 
public delegate int Damage(float randomSample); 

public class CombatantGameModel /* ... */ 
{ 
    /* ... */ 

    public Damage DamageCalculator { get; set; } 
} 
0

也許約delegates多一點的解釋應當指導你。

相關問題