开发者

Dictionary using generics

I am currently writing a resource manager for my game. This is basically a class that will handle all kinds of other 开发者_Python百科objects of different types, and each object is referred to by name (a System.String). Now this is my current implementation, but since I am using a dictionary of objects I will still need to cast every object. Is there a way to use Generics in this case? I'm not very strong on those, I tried reading up on them and it just ended up confusing me more.

public static class ResourceManager
{
    public static Dictionary<string, object> Resources { get; private set; }

    public static void LoadResources()
    {
        Resources = new Dictionary<string, object>();

        //Sample resource loading code
        Resources.Add("number", 3);
        Resources.Add("string", "bleh");

        Console.Log("Loaded " + Resources.Count + " resources.");
    }
}


Is there a need to only have one set of resources, or can you have one for each type of resource?

public class ResourceMap<T> extends Dictionary<string, T> { }

public static class ResourceManager
{
    public static ResourceMap<Font> Fonts { get; private set; }
    public static ResourceMap<Image> Images { get; private set; }
    public static ResourceMap<Sound> Sounds { get; private set; }

    public static void LoadResources()
    {
        Fonts = new ResourceMap<Font>();
        Images = new ResourceMap<Image>();
        Sounds = new ResourceMap<Sound>();

        Fonts.Add("Helvetica", new Font("Helvetica", 12, FontStyle.Regular));
        Images.Add("Example", Image.FromFile("example.png"));
    }
}


I imagine those objects all have at least a few things in common. Find that common ground and turn it into an interface that your objects implement. Then use a Dictionary<string, IMyInterface>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜