How to share derived fields between instances of the same class?

I'm working on a game in C# (XNA) and I can't figure out how to do this. Here's a really simplified version of what I have going on:

class GameObject
{
    Protected Sprite mSprite;
    Protected string filename;

    public LoadContent(ContentManager theContentManager)//XNA forces you to load content through a Content Manager which belongs to the main game class
    {
    mSprite.Load(theContentManager, filename);//the Sprite class contains a texture and methods to deal with loading images, animating, etc
    }
}

class SomeObject : GameObject
{
    public SomeObject()
    {
    filename = "someobject.png";
    }
}

Each instance of 'SomeObject' has the same Sprite, which gets loaded by the inherited loadContent method after the 'SomeObject' is initiated. Generally the LoadContent method is only called once at the beginning of the game.

However, I want to be able to add new objects after the game is currently running. It would be nice if I could make each instance of 'SomeObject' share the same sprite so that a new instance wouldn't have to load the same image again. Currently I just copy the sprite from an existing object, eg someObject2.mSprite = someObject1.mSprite But this only works if there is an existing instance of that class to copy from. What I would like to do is have mSprite be static, but if I declare it as static in the base class, all other objects will get the same sprite, and if i declare it in the derived class, I can't figure out how to load the image without re-writing the load method into every class. Is there any way to do this?


You can create a protected abstract property in the base class.

Each derived class can store a sprite in a static field and return it from the overridden property.


Would something like this suite your needs? I've created a collection of sprites that all game objects can use, if you specify a sprite with the same name as one already created it'll use the reference to the loaded sprite, if it's a new name the new sprite is loaded.

public class GameObject
{
    protected static Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();

    protected string fileName;
    protected Sprite sprite;

    public void LoadContent(ContentManager contentManager)
    {
        lock (sprites)
        {
            if (sprites.ContainsKey(fileName))
                sprite = sprites[fileName];
            else
                sprites.Add(fileName, mSprite.Load(theContentManager, filename));
        }
    }

    public GameObject(string fileName)
    {
        this.fileName = fileName;
    }
}
链接地址: http://www.djcxy.com/p/95518.html

上一篇: 从c#中的结构继承的梦想

下一篇: 如何在同一类的实例之间共享派生字段?