从实例变量访问类的静态方法?

Ray*_*Ray 4 c# inheritance xna static instance

有没有办法从实例变量访问类的静态方法/变量?我试过寻找答案,但我的搜索只找到了为什么你不能在静态方法中访问实例方法/变量.我得到为什么静态无法访问实例,但我没有得到实例无法访问静态.

这是我的情况:我是一名学生在XNA中制作一个自上而下的射击游戏,我正在尝试为每个游戏对象使用静态Texture2D.我有一个类游戏物体是奠定基础的所有其他类,与其他两大类GameBot和弹分别奠定了机器人和弹丸的基础知识.我的问题也与这种继承有关.我有GameBot和弹丸类中的所有碰撞码,和其他类,如PlayerShip/EnemyShip或炮弹/导弹从他们那里继承.

我遇到的问题是我想从一个我不知道该类的实例变量访问一个类方法/变量.我的意思是,我通过我的方法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
    }
}
Run Code Online (Sandbox Code Playgroud)

这场比赛是一种继承运动.我想尝试在层次结构中较高的类中保留尽可能多的代码,并且只编写每个类中的基本差异.我决定使用静态纹理的原因是我可以在每个GameBot中保留一个Projectile数组,但是能够即时修改Projectile(炮弹,导弹等)在该阵列中的某个位置.没有静态射弹,我每次切换弹丸时都必须分配精灵.我之所以需要一个Projectile阵列,所以我可以轻松添加另一个Projectile而无需在任何地方添加代码.

有没有办法从实例变量访问静态方法/变量?如果没有,有任何其他方法可以保持碰撞代码尽可能通用吗?

Mat*_*ted 6

从实例访问它的简单方法是这样的......

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;
}
Run Code Online (Sandbox Code Playgroud)

...然后,您可以.GetTextureData()从外部变量调用,而不必单独管理/维护静态调用.