繁体   English   中英

使用反射将嵌套类传递给构造函数

[英]Pass nested class to constructor using reflection

我需要将嵌套类传递给另一个具有如下构造函数的ViewModel

 public CityEditViewModel(CityListViewModel.CityInfo info)
        {
            Model = Library.CityEdit.GetItem(info.Model.CityID);
        }

我从中获取数据的类是CityListViewModel ,其中是嵌套的类CityInfo

详细。 我有一个datagrid其项目类型为CityInfo 好吧,当我从datagrid选择该项目时,它应该打开一个新的ViewModel ,它是CitiyEditViewModel (它应该将该类发送到上面的我的构造函数中)。

我尝试了以下方法:

Type EditClass = GetMyClass(subClass); //getting my CityEditViewModel
ConstructorInfo editConstructor = EditClass.GetConstructor(new Type[] { ChildClass }); // getting the constructor of that class
IScreen screen = (IScreen)(Activator.CreateInstance(EditClass, editConstructor )); //this part activates the window


    //GetMyClass method
    public Type GetMyClass(string type)
    {
        return Type.GetType(type);
    }

但是我得到的方法不存在异常。

在此行中,您尝试调用构造函数CityEditViewModel(CityEditViewModel.CityInfo)

IScreen screen = (IScreen)(Activator.CreateInstance(EditClass, 
    editConstructor )); 

CreateInstance重载采用一个或多个参数。 第一个是要构造的类的Type 第二个及后续参数是您希望其传递给构造函数的参数。 它使用反射来查找按该顺序匹配该组参数的构造函数。 如果找到一个,则调用它来创建该类型的实例。

您正在传递类型为ConstructorInfo的构造函数参数。 CityEditViewModel没有采用该类型参数的构造函数。 该方法不存在。 因此,例外。 我收到System.MissingMethodException消息, "Constructor on type 'CityEditViewModel' not found." 如果该消息表明未找到某些特定的构造函数,则该消息会更好,但是我看到的情况更糟。

而是将其传递给CityEditViewModel.CityInfo

var cityInfo = whateverThingUserClickedOn as CityEditViewModel.CityInfo;

IScreen screen = (IScreen)(Activator.CreateInstance(EditClass, 
    cityInfo )); 

但是该转换是为了您的利益,而不是Activator.CreateInstance() 构造函数参数是object ,因此不需要强制转换:

IScreen screen = (IScreen)(Activator.CreateInstance(EditClass, 
    whateverThingUserClickedOn )); 

并删除下一行; 您不需要它。 Activator.CreateInstance()根据您提供的参数类型为您找到构造函数。

ConstructorInfo editConstructor = EditClass.GetConstructor(
    new Type[] { ChildClass }); // getting the constructor of that class

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM