开发者

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜