[英]Dynamically creating a class of generic type
I have a class like this 我有这样的课
public class ViewModelBase<T> : Notifier
{
private readonly string _tabHeaderPath;
private readonly T _view;
public ViewModelBase(T view)
{
_view = view;
}
public ViewModelBase(T view, string tabHeaderPath)
{
_view = view;
_tabHeaderPath = tabHeaderPath;
}
public T View
{
get { return _view; }
}
public string TabHeaderPath
{
get { return _tabHeaderPath; }
}
}
I want to get an object of this using reflection something like this. 我想使用类似这样的反射来获取此对象。
object PresenterBase= null;
Assembly assembly = Assembly.GetExecutingAssembly();
object objView = null;
// Walk through each type in the assembly looking for our class
foreach (Type type in assembly.GetTypes())
{
if (type.IsClass == true)
{
if (type.FullName.EndsWith("." + "GeneralEnquiryViewModel"))
{
// create an instance of the object
foreach(Type objType2 in assembly.GetTypes())
{
if(objType2.IsClass==true)
{
if (objType2.FullName.EndsWith("." + "GeneralEnquiryView"))
{
objView = Activator.CreateInstance(objType2);
break;
}
}
}
ConstructorInfo ctor = type.GetConstructor(new[] { typeof(GeneralEnquiryView), typeof(string) });
PresenterBase= ctor.Invoke(new object[] { objView, "GeneralEnquiry" });
}
}
}
I am able to do like this: 我可以这样做:
ViewModelBase<GeneralEnquiryView> objPresenter = GeneralEnquiryViewModel(PresenterBase);
But i want to replace GeneralEnquiryView to objview and GeneralEnquiryViewModel to PresenterBase so that i get an instance of objPresenter. 但是我想将GeneralEnquiryView替换为objview,将GeneralEnquiryViewModel替换为PresenterBase,以便获得objPresenter的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.