【发布时间】:2018-09-30 13:36:55
【问题描述】:
我正在使用 Microsoft XNA Game Studio 4.0 作为我的项目的模板。
在这个项目中,我有一个用于所有实体、射弹等的基类,称为 Sprite。
我打算使用单例来处理所有Sprites,因此如果以前使用过它,我不必每次需要它时都创建一个新的Sprite。
这是首选,因为 Sprites 有一个 Texture2D 字段以及其他可能占用内存的字段,前提是创建了足够多的 Sprites。
这里是我的Texture2Dsingleton 的一部分作为参考:
public static class TextureManager{
private static Dictionary<string, Texture2D> allTextures = new Dictionary<string, Texture2D>();
public static Texture2D GetTexture(string name){
if(allTextures.ContainsKey(name))
return allTextures[name];
... //Code to handle and create a new key is omitted for simplicity's sake
return newTexture; //The new texture created from the "name" key
}
}
这个单例比每次需要时都从内容管道创建新的Texture2D 更受欢迎。代码来源于this answer。
在规划Sprite 单例时,我突然想到,必须进行拳击才能使单例在Dictionary 上工作,因为基本上我的所有实体和射弹类都将继承Sprite 类。
问题:
在一个Dictionary 上装箱/拆箱是否比为每种Sprite 设置多个Dictionarys 更有效?
【问题讨论】: