Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.");
    }
}
like image 710
Alex Turpin Avatar asked Oct 15 '22 09:10

Alex Turpin


2 Answers

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"));
    }
}
like image 59
Samir Talwar Avatar answered Oct 20 '22 16:10

Samir Talwar


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>.

like image 40
Joel Coehoorn Avatar answered Oct 20 '22 15:10

Joel Coehoorn