使用反射加载泛型类的具体类型

时间:2010-12-21 12:59:54

标签: c# generics reflection

基本上我们的产品的旧版本中有一些代码使用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;
    }}

此致 杰米

1 个答案:

答案 0 :(得分: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
}

这消除了通过反射找出泛型参数问题的必要性。

此致 杰米