2010-12-21 68 views
0

基本上我們有一些來自我們產品的舊版本的代碼,它使用XML來驅動外部代碼的加載。使用反射加載通用類的具體類型

e.g

ObjectHandle handle = Activator.CreateInstance(
             information.AssemblyName, 
             information.TypeName); 

loadedObject = (T)handle.Unwrap(); 

然而,試圖加載上它具有一個通用的參數類型時失敗。現在我知道在編譯時類型將會是什麼(可能類型也是外部的,並且可能會根據情況而改變(僅在xml中))。

有沒有加載的類類型的一種方式:其中T是類型ActionSettings

public class MockTestRunner<T> : IRunner<T> where T : class 
{ 
    #region IRunner<T> Members 

    public T Run(string runnerXml) 
    { 
     MvcActionSettings mvcActionSettings = XmlSerialiser.XmlDeserialise<MvcActionSettings>(runnerXml); 

     IMvcActionSettingsCreator creator = new MockPassThroughActionSettingsGenerator(); 
     var v = creator.Create(mvcActionSettings); 
     return v as T; 
    } 

    public void Initialise(IWizardManagerBase manager) 
    { 

    } 
} 

    /// <summary> 
/// An MVC controller settings object. 
/// </summary> 
[Serializable] 
public class ActionSettings 
{ 
    /// <summary> 
    /// Initializes a new instance of the ActionSettings class. 
    /// </summary> 
    public ActionSettings() 
    { 
     PartialViews = new List<PartialViewEntity>(); 
    } 

    public ActionSettings(bool endOfWizard) 
    { 
     EndOfWizard = endOfWizard; 
    } 

    public bool EndOfWizard 
    { 
     get; 
     set; 
    }} 

問候, 傑米

+0

http://stackoverflow.com/questions/266115/pass-an-instantiated-system-type-as-a-type-parameter-for-a-generic-class – 2010-12-21 13:03:31

+0

不相當,在這種情況下,Type參數在執行程序集或框架內是明確的。我需要它來加載一個外部類型。 – Jamie 2010-12-21 13:28:36

回答

1

咩,過於複雜的一如既往的。不知道我應該

public class MockTestControllerRunner : IRunner<Interfaces.ActionSettings> 
{ 
    #region IRunner<T> Members 

    public ActionSettings Run(string runnerXml) 
    { 
     MvcActionSettings mvcActionSettings = XmlSerialiser.XmlDeserialise<MvcActionSettings>(runnerXml); 

     IMvcActionSettingsCreator creator = new MockPassThroughActionSettingsGenerator(); 
     Interfaces.ActionSettings v = creator.Create(mvcActionSettings); 
     return v; 
    } 

    #endregion 

    #region IRunnerWorkflowSubscriber Members 

    public void Initialise(IWizardManagerBase manager) 
    { 

    } 

    #endregion 
} 

這消除了周圍的泛型參數問題找到客場與反思的必要。

問候, 傑米