![](/img/trans.png)
[英]Construct an instance of a concrete type of a generic, using reflection at runtime
[英]Loading a concrete type of a generic class using reflection
基本上,我們從產品的舊版本中獲得了一些代碼,這些代碼使用XML來驅動外部代碼的加載。
例如
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;
}}
此致傑米
嗯,一如既往的復雜。 沒意識到我應該做:
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
}
這消除了尋找與反射有關的通用參數問題的需要。
此致傑米
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.