我有一个带有"BlockType"枚举的图形程序.根据州的不同,这可能是以下几种方式之一:木材,石材,草坪等.
最初,每种可能性都需要进行各种纹理操作,但是由于一些重构,枚举仅用作整数,并且不再需要switch语句.即:
BlockType someFoo = someObj.blockType;
Texture usedTexture = textureLookupArray[(int) someFoo];
Run Code Online (Sandbox Code Playgroud)
但作为一个副作用,Enum字符串完全是多余的!即使BlockType 5被定义为"Carpet","Gravel"或"JQuery",我也可以将"Stone"纹理放在第5位!
我的第一个想法是简单地重写BlockType来定义"Material1,Material2等".而不是硬编码(和潜在的冲突!)值,但这实际上是否有用?
可能会有一些好处,我忽略了将BlockType保持为枚举,或者我应该将其切换到常规的Int以减少混淆?
小智 7
为什么在字典会更好,更好的时候使用数组呢?
private Dictionary<BlockType, Texture> _textures =
new Dictionary<BlockType, Texture>
{
{ BlockType.Wood, new WoodTexture() },
{ BlockType.Metal, new MetalTexture() },
//etc
}
Run Code Online (Sandbox Code Playgroud)
使用起来更优雅
var tex = _textures[someObj.blockType];
Run Code Online (Sandbox Code Playgroud)