Possible to combine generics and reflection in this situation?
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() {
开发者_JS百科 ModelType = typeof(TModel),
TemplateString = templateString,
TemplateName = "Rzr" + Guid.NewGuid().ToString("N")
};
}
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.
精彩评论