1

我一直在试验一个应用程序,它将扫描程序集,检查任何形式的类,然后查看它们有哪些成员。

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

 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

4

2 回答 2

5

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

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

你应该做:

     Object form = Activator.CreateInstance(type);       

顺便说一句,我不会使用类的名称来检查它是否从 Form 派生,您可以使用 IsSubclassOf:

     type.IsSubclassOf(typeof(Form));
于 2011-10-03T10:42:18.590 回答
1

对象形式 = Activator.CreateInstance( type );

于 2011-10-03T10:40:56.617 回答