开发者

Dictionary using generics

开发者 https://www.devze.com 2022-12-19 23:43 出处:网络
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

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

精彩评论

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

关注公众号