动态创建泛型类型的类

本文关键字:泛型类型 创建 动态 | 更新日期: 2023-09-27 18:27:27

我有一个类似的类

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; }
    }
}

我想用反射得到一个这样的物体。

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" });
         }
    }
}

我可以这样做:

ViewModelBase<GeneralEnquiryView> objPresenter = GeneralEnquiryViewModel(PresenterBase);

但我想将GeneralEnquiryView替换为objview,将GeneralEn奎ryViewModel替换为PresenterBase,这样我就可以获得objPresenter的实例。

动态创建泛型类型的类

我认为这是您的解决方案:https://stackoverflow.com/questions/34383784/c-sharp-reflection-invoke-constructor-of-generic-class