2011-05-06 24 views
1

我想調用一些功能,需要在泛型情況下傳遞一個類型。我只有一個類型的字符串表示和包含該類型的程序集。 這是可能的嗎?可能在這種情況下將泛型和反射相結合?

召喚:

var typeName = "CustomNamespace.CustomType"; 

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

功能:

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") 
      }; 
    } 

回答

2

好了,你可以使用MethodInfo.MakeGenericMethod

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

使用帶有反射泛型是對接醜陋,但它作品。

+0

'Generator'不是一個靜態類,它是一個需要調用該方法的實例。我在這裏閱讀你的答案(http://stackoverflow.com/questions/919826/invoke-method-by-methodinfo),我正在尋找使我的課變爲靜態的可能性。然而,是否有可能在一個實例上做這種反射魔術? – Ropstah 2011-05-06 15:22:01

+0

@Ropstah:這是我們第一次聽說'Generator'類。你可以肯定地使用反射與實例,但我不知道目前的問題是什麼。 – 2011-05-06 15:27:06

+0

當我評論時,我領先於自己。 'Invoke'把對象實例作爲第一個參數,所以它可以工作! – Ropstah 2011-05-06 15:37:40