简体   繁体   中英

Loading a concrete type of a generic class using reflection

Basically we had some code from a older version of our product which used XML to drive the loading of external code.

eg

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

loadedObject = (T)handle.Unwrap();

However, this fails when attempting to load a type which has a generic parameter on it. Now I do know what the type is going to be at compile time (likely that the type will also be external and may change depending on situation (in the xml only)).

Is there a way of loading a class of type: where T is of type 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;
    }}

Regards, Jamie

Meh, overcomplicated as always. Didn't realise I should do:

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
}

This removes the need for finding away around the generic parameter issue with reflection.

Regards, Jamie

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM