1

I'm trying to call some functionality that requires a type to be passed in a generics situation. I only have a string representation of the type and the assembly that contains the type. Is this possible somehow?

The call:

var typeName = "CustomNamespace.CustomType";

//CustomNamespace.CustomType should be replaced with typeName
Generator.RegisterTemplate<CustomNamespace.CustomType>(); 

The function:

    public void RegisterTemplate<TModel>(string templateName, 
        string templateString)
    {
        templateItems[TranslateKey(typeof(TModel), templateName)] = 
            new RazorTemplateEntry() { 
                ModelType = typeof(TModel), 
                TemplateString = templateString, 
                TemplateName = "Rzr" + Guid.NewGuid().ToString("N") 
            };
    }
casperOne
  • 73,706
  • 19
  • 184
  • 253
Ropstah
  • 17,538
  • 24
  • 120
  • 194

1 Answers1

2

Well, you can use MethodInfo.MakeGenericMethod:

Type type = Type.GetType(typeAndAssemblyName);
MethodInfo method = typeof(Foo).GetMethod("RegisterTemplate");
MethodInfo generic = method.MakeGenericMethod(type);
generic.Invoke(...);

Using generics with reflection is butt-ugly, but it works.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • `Generator` isn't a static class, it's an instance on which the method needs to be invoked. I'm reading your answer here (http://stackoverflow.com/questions/919826/invoke-method-by-methodinfo) and I'm looking at the possibility to make my class static. Is it possible however to do this reflection magic on an instance? – Ropstah May 06 '11 at 15:22
  • @Ropstah: This is the first we've heard about the `Generator` class. You can definitely use reflection with an instance, but I'm not sure what the issue is at the moment. – Jon Skeet May 06 '11 at 15:27
  • I was ahead of myself when I commented. `Invoke` takes the object instance as a first parameter so it will work! – Ropstah May 06 '11 at 15:37