创建表单实例时出现反射错误

时间:2011-10-03 10:27:56

标签: c# reflection system.reflection

我一直在尝试扫描程序集的应用程序,检查表单中的任何类,然后查看它们拥有的成员。

我用来查询程序集的代码是:

 Assembly testAssembly = Assembly.LoadFile(assemblyPath);

 Type[]  types = testAssembly.GetTypes();
 textBox1.Text = "";

 foreach (Type type in types)
 {
     if (type.Name.StartsWith("Form"))
     {
         textBox1.Text += type.Name + Environment.NewLine;

         Type formType = testAssembly.GetType();
         Object form = Activator.CreateInstance(formType);       
      }
 }

我用它来查询标准表格:

 using System;
 using System.ComponentModel;
 using System.Windows.Forms;

 namespace TestForm
 {
     public partial class Form1 : Form
     {
         public Form1()
         {
            InitializeComponent();
         }
     }
 }

我的问题是,当代码尝试Activator.CreateInstance(formType)时,我得到一个例外说明:"No parameterless constructor defined for this object." 我还可以通过检查formType看到'DeclaringMethod:'formType.DeclaringMethod'抛出类型'System.InvalidOperationException''的异常

我不明白错误信息,因为表单有一个标准的构造函数,我错过了一些非常明显的东西吗?

编辑:type.Name显示代码尝试实例化为Form1的类型。

2 个答案:

答案 0 :(得分:5)

您正在尝试创建Assembly的实例,而不是您的表单:

     Type formType = testAssembly.GetType();
     Object form = Activator.CreateInstance(formType);       

你应该这样做:

     Object form = Activator.CreateInstance(type);       
顺便说一句,我不会使用类的名称来检查它是否派生自Form,你可以使用IsSubclassOf:

     type.IsSubclassOf(typeof(Form));

答案 1 :(得分:1)

对象形式= Activator.CreateInstance(类型);

相关问题