1

Im making a XNA contentloader:

public object[] LoadIt(KeyValuePair<Type,string>[] resources, ContentManager content)
{
    object[] result = new object[resources.Length];
    for(int i=0;i<result.Length;i++)
    {
        result[i] = content.Load<resources[i].Key>(resources[i].Value);
    }
    return result;
}

but apparenty you're not allowed to pass a generic type from a variable, so how do i solve this then?

also if you pass the type as a generic to the method itself, then i still need the object calling the method to get the type from variable, since ill be making a file that declares the files to load and from the strings of that file, i need to pass the type and path of the files to load

MooshBeef
  • 279
  • 1
  • 5
  • 15

2 Answers2

1

This is an XNA-specific answer to your question, but you don't need to do that!

You could just replace this:

content.Load<resources[i].Key>(resources[i].Value);

With this:

content.Load<object>(resources[i].Value);

XNA figures out the appropriate type on its own at runtime, from the content file itself. The generic is just for convenience and type safety.

If you wanted to verify the type of the loaded object for yourself, you could do something like this:

if(result[i].GetType() != resources[i].Key
        && !result[i].GetType().IsSubclassOf(resources[i].Key))
{
    throw new InvalidOperationException();
}

Of course, one could ask why you are making a "contentloader"? I don't have enough information about what you are doing - but it looks like it might be unnecessary. XNA's ContentManager already implements (customisable) caching of loaded objects - so it's likely that you could (and should) just use it directly.

Andrew Russell
  • 26,924
  • 7
  • 58
  • 104
0

You simply can't as the type is not compile-time constant.

What you can do is to use reflection without a problem as you only need object as return value:

public object[] LoadIt(KeyValuePair<Type,string>[] resources, ContentManager content)
{
    object[] result = new object[resources.Length];
    for(int i=0;i<result.Length;i++)
    {
        result[i] = content
                      .GetType()
                      .GetMethod("Load")
                      .MakeGenericMethod(resources[i].Key)
                      .Invoke(content, new object[] { resources[i].Value });
    }
    return result;
}
Matten
  • 17,365
  • 2
  • 42
  • 64