开发者

Possible to combine generics and reflection in this situation?

开发者 https://www.devze.com 2023-03-03 03:47 出处:网络
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 possi

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

精彩评论

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

关注公众号