【问题标题】:Use value of a string to create new form object使用字符串的值创建新的表单对象
【发布时间】:2011-01-01 21:34:48
【问题描述】:

我启动了一个主窗体,然后它可以转到我创建的任何其他窗体。但更重要的是,我编写了一个我调用的类,它返回一个带有要转到的表单名称的字符串。

目前我没有这个工作,所以我要从一个表单到另一个表单(静态编写的链接代码):

this.Hide();
CloudAccess nextForm1 = new CloudAccess(); 
   //Where CloudAccess is the class of the next form.
nextForm1.ShowDialog();

我想要的是这样的:

FormController pick = new FormController();
   //Where FormController is the Class I create an object of and ask what's next
string next = pick.whereToGo(); //lets say it returns "CloudAccess"
this.Hide();
next nextForm1 = new next(); //next is desired to be the contents of the string
nextForm1.ShowDialog();

问题是我不知道如何使用返回的字符串来制作新对象并使用它。我一直在看类似这样的调用和反射主题:Use string value to create new instance 但我是 C# 新手,我不知道如何将它应用到这个场景中。

想法?谢谢!

【问题讨论】:

  • 只要让 whereToGo() 返回一个表单,而不是一个字符串。控制器在创建视图实例时永远不会遇到问题。
  • 如何让它返回表单? public form whereToGo(){ return CloudAccess; } ?
  • @Dial - 它没有回答问题。根据我的经验,最好在 cmets 中对前额进行二乘四操作。
  • @Hans 这将是一个答案,因为它可以让我得到相同的结果。我只是不确定我如何将方法变成表单..
  • @cvo - 循环往复:为什么你的代码中有一个不知道如何创建视图的控制器?对象模型是否妨碍了完成工作?我当然不知道为什么。

标签: c# winforms string


【解决方案1】:

这是 fejejosco 所说的工作代码:

string asdf = "CloudAccess";
Type CAType = Type.GetType("namespace." + asdf);
Form nextForm2 = (Form)Activator.CreateInstance(CAType);
nextForm2.ShowDialog();

谢谢!

【讨论】:

    【解决方案2】:

    获取表单的类型:Type.GetType("name.space." + formname),所以如果你的类是name.space.CloudAccessForm,那么传入CloudAccessForm作为formname,它会给你类型。然后你可以用Activator.CreateInstance(type) 实例化它。然后将其转换为Form,并显示出来。

    【讨论】:

    • 字符串 asdf = "CloudAccess";类型 CAType = Type.GetType("NameSpace." + asdf);激活器.CreateInstance(CAType);表单 nextForm2 = (Form)CAType; nextForm2.ShowDialog();这给了我错误:“无法将类型 'System.Type' 转换为 'System.Windows.Forms.Form'
    • 投射实例,而不是类型。
    猜你喜欢
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2020-09-19
    • 2014-04-12
    相关资源
    最近更新 更多