簡體   English   中英

從實例變量訪問類的靜態方法?

[英]accessing a class's static method from an instance variable?

有沒有辦法從實例變量訪問類的靜態方法/變量? 我嘗試搜索答案,但是我的搜索只能找到為什么您不能在靜態方法中訪問實例方法/變量的原因。 我明白了為什么靜態無法訪問實例,但是我沒有實例無法訪問靜態。

這是我的情況:我是一名學生,在XNA中制作自上而下的射擊游戲,並且試圖為每個游戲對象使用靜態Texture2D。 我有一個GameObject類,它為每個其他類奠定基礎,而另外兩個主要類GameBot和Projectile分別為機器人和射彈奠定了基礎。 我的問題也與繼承有關。 我在GameBot和Projectile類中擁有所有碰撞代碼,其他類(如PlayerShip / EnemyShip或Cannonball / Missile)都從它們繼承。

我遇到的問題是我想從我不知道該類的實例變量中訪問類方法/變量。 我的意思是,我向我的方法傳遞了一個GameBot變量,但它可以是PlayerShip,EnemyShip或GameBot的任何其他子代,並且每個都有不同的靜態紋理數據。

class GameBot : GameObject
{
    static protected Texture2D texture;
    static internal Color[] textureData;

    //etc...

    internal bool DidHitEnemy(GameBot enemyGameBot)
    {
        //Here, I want to access enemyGameBot.textureData
        //to do pixel-by-pixel collision
        //but A) enemyGameBot.textureData doesn't work
        //and B) enemyGameBot's class could be any child of GameBot
        //so I can't just use GameBot.textureData
    }

    static internal virtual Color[] GetTextureData()
    {
        return textureData;
        //I even thought about coding this function in each child
        //but I can't access it anyway
    }
}

這個游戲是一種繼承的練習。 我想嘗試在層次結構中較高級別的類中保留盡可能多的代碼,並且僅對每個類中的本質區別進行編碼。 我決定使用靜態紋理的原因是,我可以在每個GameBot中保留一個投射物陣列,但可以即時修改該陣列中某個位置上的投射物(炮彈,導彈等)。 如果沒有靜態彈丸,則每次切換彈丸時都必須分配精靈。 我之所以需要一個Projectile數組,是因為我可以輕松地添加另一個Projectile,而不必到處添加代碼。

有沒有辦法從實例變量訪問靜態方法/變量? 如果沒有,關於保持沖突代碼盡可能通用的另一種建議?

從實例訪問此內容的簡單方法是這樣的...

public Color[] GetTextureData()
{        
    //note that `GameBot.` isn't required but I find it helpful to locate static 
    //calls versus `this.` for instance methods
    return GameBot.GetTextureDataInternal(); 
}

static internal Color[] GetTextureDataInternal()
{
    return textureData;
}

...然后您可以從外部變量中調用.GetTextureData() ,而不必分別管理/維護靜態調用。

    class Gamebot : GameObject
{
    static Texture2D DefaultTexture;
    public virtual Texture2D Texture {get{return Gamebot.DefaultTexture;}}



    //etc...

    internal bool DidHitEnemy(Gamebot enemyGameBot)
    {

      //  enemyGameBot.Texture; // this will give you the texture of the enemyGameBot 
    }


}
class SmartBot : Gamebot
{
    static new Texture2D DefaultTexture;
    public override Texture2D Texture { get { return SmartBot.DefaultTexture; } }

}

在LoadContent中,您將分配每個類的紋理

SmartBot.DefaultTexture = null;
GameBot.DefaultTexture =null;

您可以對texturedata做同樣的事情

編輯:順便說一句,如果您有紋理,則可以提取Color [] TextureData,因此您需要將其保持為靜態

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM