开发者

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.

e.g

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 : cla开发者_开发技巧ss
{
    #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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜